CommunityCodierung & Entwicklunggithub.com

nextjs-typescript

Production-grade Next.js 14+ with TypeScript. Use this skill for App Router, Server Components, Server Actions, API routes, authentication, state management, performance optimization, SEO, and deployment. Triggers on Next.js, React, TypeScript, SSR/SSG/ISR tasks.

Was ist nextjs-typescript?

nextjs-typescript is a Claude Code agent skill that production-grade Next.js 14+ with TypeScript. Use this skill for App Router, Server Components, Server Actions, API routes, authentication, state management, performance optimization, SEO, and deployment. Triggers on Next.js, React, TypeScript, SSR/SSG/ISR tasks.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/CloudNinjaDev/claude-code-production-skills/tree/HEAD/skills/nextjs-typescript

Installed? Explore more Codierung & Entwicklung skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Next.js + TypeScript — Production Skill

Project Structure (App Router)

src/
├── app/
│   ├── (auth)/              # Route group — auth pages
│   │   ├── login/page.tsx
│   │   └── signup/page.tsx
│   ├── (dashboard)/         # Route group — protected
│   │   └── dashboard/
│   │       ├── layout.tsx
│   │       └── page.tsx
│   ├── api/                 # API routes
│   │   └── webhooks/
│   │       └── route.ts
│   ├── globals.css
│   ├── layout.tsx           # Root layout
│   └── page.tsx
├── components/
│   ├── ui/                  # Shadcn/base components
│   └── features/            # Feature-specific components
├── lib/
│   ├── db.ts                # DB client (Prisma / Drizzle)
│   ├── auth.ts              # Auth config (NextAuth / Clerk)
│   └── utils.ts
├── hooks/                   # Custom React hooks
├── types/                   # Global TypeScript types
├── actions/                 # Server Actions
└── middleware.ts

TypeScript Conventions

// Always type component props explicitly
type ButtonProps = {
  variant: 'primary' | 'secondary' | 'ghost'
  size?: 'sm' | 'md' | 'lg'
  isLoading?: boolean
  onClick?: () => void
  children: React.ReactNode
}

// Use discriminated unions for API responses
type ApiResult<T> =
  | { success: true; data: T }
  | { success: false; error: string; code: number }

// Infer types from Zod schemas — single source of truth
import { z } from 'zod'
const UserSchema = z.object({
  id: z.string().cuid(),
  email: z.string().email(),
  name: z.string().min(1).max(100),
  role: z.enum(['admin', 'user', 'moderator']),
})
type User = z.infer<typeof UserSchema>

// Generic fetch wrapper with type safety
async function fetchApi<T>(
  url: string,
  options?: RequestInit
): Promise<ApiResult<T>> {
  try {
    const res = await fetch(url, options)
    if (!res.ok) return { success: false, error: await res.text(), code: res.status }
    return { success: true, data: await res.json() as T }
  } catch (e) {
    return { success: false, error: String(e), code: 0 }
  }
}

Server Components vs Client Components

// Server Component (default) — no 'use client'
// Can: async/await, access DB directly, read env vars
// Cannot: useState, useEffect, browser APIs, event handlers

// app/dashboard/page.tsx
import { db } from '@/lib/db'
import { auth } from '@/lib/auth'

export default async function DashboardPage() {
  const session = await auth()
  const data = await db.user.findMany({ where: { id: session.user.id } })
  return <UserList users={data} />
}

// Client Component — needs 'use client' at top
'use client'
import { useState, useTransition } from 'react'

export function InteractiveForm() {
  const [isPending, startTransition] = useTransition()
  // Can use hooks, event handlers, browser APIs
}

Server Actions

// actions/user.ts
'use server'

import { revalidatePath } from 'next/cache'
import { z } from 'zod'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'

const UpdateProfileSchema = z.object({
  name: z.string().min(1).max(100),
  bio: z.string().max(500).optional(),
})

export async function updateProfile(formData: FormData) {
  const session = await auth()
  if (!session) throw new Error('Unauthorized')

  const parsed = UpdateProfileSchema.safeParse({
    name: formData.get('name'),
    bio: formData.get('bio'),
  })
  if (!parsed.success) return { error: parsed.error.flatten() }

  await db.user.update({
    where: { id: session.user.id },
    data: parsed.data,
  })

  revalidatePath('/dashboard/profile')
  return { success: true }
}

// Usage in component
'use client'
import { updateProfile } from '@/actions/user'
import { useFormState } from 'react-dom'

export function ProfileForm() {
  const [state, action] = useFormState(updateProfile, null)
  return <form action={action}>...</form>
}

Data Fetching Patterns

// Parallel data fetching in Server Components
export default async function Page({ params }: { params: { id: string } }) {
  const [user, posts, analytics] = await Promise.all([
    fetchUser(params.id),
    fetchUserPosts(params.id),
    fetchAnalytics(params.id),
  ])
  return <Dashboard user={user} posts={posts} analytics={analytics} />
}

// Streaming with Suspense
import { Suspense } from 'react'

export default function Page() {
  return (
    <>
      <StaticHeader />
      <Suspense fallback={<Skeleton />}>
        <SlowDataComponent />  {/* Streams in when ready */}
      </Suspense>
    </>
  )
}

// Incremental Static Regeneration (ISR)
export const revalidate = 3600 // Revalidate every hour

// On-demand revalidation
import { revalidatePath, revalidateTag } from 'next/cache'
revalidatePath('/products')
revalidateTag('products')

// fetch with cache tags
const data = await fetch('https://api.example.com/products', {
  next: { tags: ['products'], revalidate: 3600 }
})

Middleware

// middleware.ts — runs at the edge before every request
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { auth } from '@/lib/auth'

export async function middleware(request: NextRequest) {
  const session = await auth()
  const isAuthPage = request.nextUrl.pathname.startsWith('/login')
  const isProtected = request.nextUrl.pathname.startsWith('/dashboard')

  if (isProtected && !session) {
    return NextResponse.redirect(new URL('/login', request.url))
  }
  if (isAuthPage && session) {
    return NextResponse.redirect(new URL('/dashboard', request.url))
  }

  // Add security headers
  const response = NextResponse.next()
  response.headers.set('X-Frame-Options', 'DENY')
  response.headers.set('X-Content-Type-Options', 'nosniff')
  return response
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
}

Route Handlers (API Routes)

// app/api/users/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { auth } from '@/lib/auth'

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  const session = await auth()
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const user = await db.user.findUnique({ where: { id: params.id } })
  if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 })

  return NextResponse.json(user)
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  const session = await auth()
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const body = await request.json()
  // validate with zod, update, return
}

Authentication (NextAuth v5 / Auth.js)

// lib/auth.ts
import NextAuth from 'next-auth'
import { PrismaAdapter } from '@auth/prisma-adapter'
import Google from 'next-auth/providers/google'
import Credentials from 'next-auth/providers/credentials'
import { db } from './db'
import bcrypt from 'bcryptjs'

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(db),
  providers: [
    Google,
    Credentials({
      async authorize(credentials) {
        const user = await db.user.findUnique({ where: { email: credentials.email as string } })
        if (!user || !user.password) return null
        const valid = await bcrypt.compare(credentials.password as string, user.password)
        return valid ? user : null
      },
    }),
  ],
  callbacks: {
    session({ session, user }) {
      session.user.id = user.id
      session.user.role = user.role
      return session
    },
  },
  pages: { signIn: '/login' },
})

State Management

// Zustand for global client state (prefer server state via React Query)
import { create } from 'zustand'
import { persist } from 'zustand/middleware'

type CartStore = {
  items: CartItem[]
  addItem: (item: CartItem) => void
  removeItem: (id: string) => void
  total: () => number
}

export const useCartStore = create<CartStore>()(
  persist(
    (set, get) => ({
      items: [],
      addItem: (item) => set((s) => ({ items: [...s.items, item] })),
      removeItem: (id) => set((s) => ({ items: s.items.filter(i => i.id !== id) })),
      total: () => get().items.reduce((sum, i) => sum + i.price * i.qty, 0),
    }),
    { name: 'cart-storage' }
  )
)

// TanStack Query for server state
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'

function useUser(id: string) {
  return useQuery({
    queryKey: ['user', id],
    queryFn: () => fetchApi<User>(`/api/users/${id}`),
    staleTime: 5 * 60 * 1000,
  })
}

Performance & SEO

// Metadata API
import type { Metadata } from 'next'

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const product = await fetchProduct(params.slug)
  return {
    title: product.name,
    description: product.description,
    openGraph: {
      images: [{ url: product.image, width: 1200, height: 630 }],
    },
  }
}

// Image optimization
import Image from 'next/image'
<Image src={url} alt={alt} width={800} height={600} priority sizes="(max-width: 768px) 100vw, 50vw" />

// Font optimization
import { Inter, Geist_Mono } from 'next/font/google'
const inter = Inter({ subsets: ['latin'], display: 'swap' })

// Dynamic import for code splitting
import dynamic from 'next/dynamic'
const HeavyChart = dynamic(() => import('@/components/HeavyChart'), {
  loading: () => <Skeleton />,
  ssr: false,
})

Environment Variables

# .env.local (never commit)
DATABASE_URL="postgresql://..."
NEXTAUTH_SECRET="..."
NEXTAUTH_URL="http://localhost:3000"

# .env.example (commit this)
DATABASE_URL="postgresql://user:pass@localhost:5432/mydb"
// lib/env.ts — validated env vars with t3-env
import { createEnv } from '@t3-oss/env-nextjs'
import { z } from 'zod'

export const env = createEnv({
  server: {
    DATABASE_URL: z.string().url(),
    NEXTAUTH_SECRET: z.string().min(32),
  },
  client: {
    NEXT_PUBLIC_APP_URL: z.string().url(),
  },
  runtimeEnv: {
    DATABASE_URL: process.env.DATABASE_URL,
    NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,
    NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,
  },
})

Error Handling

// app/error.tsx — catches runtime errors in segment
'use client'
export default function Error({ error, reset }: { error: Error; reset: () => void }) {
  return (
    <div>
      <h2>Something went wrong</h2>
      <button onClick={reset}>Try again</button>
    </div>
  )
}

// app/not-found.tsx
export default function NotFound() {
  return <div>404 - Page not found</div>
}

// Global error boundary for layout errors
// app/global-error.tsx
'use client'
export default function GlobalError({ error, reset }: { error: Error; reset: () => void }) {
  return <html><body><h2>Critical Error</h2><button onClick={reset}>Reset</button></body></html>
}

Key Libraries (Recommended Stack)

CategoryLibraryNotes
ORMPrisma or DrizzlePrisma for DX, Drizzle for performance
AuthAuth.js v5 (NextAuth)Or Clerk for managed auth
ValidationZodUse everywhere
UIshadcn/ui + Tailwind CSSCopy-paste component model
StateZustand + TanStack QueryClient + server state
FormsReact Hook Form + ZodWith Server Actions fallback
EmailResend + React Email
PaymentsStripeSee payment-gateway skill
Env@t3-oss/env-nextjsType-safe env vars
Error trackingSentry
AnalyticsVercel Analytics or PostHog

Common Pitfalls

  • Never put secrets in NEXT_PUBLIC_* env vars
  • Don't use export const dynamic = 'force-dynamic' unless you need it — kills static optimization
  • Avoid useEffect for data fetching — use Server Components or TanStack Query
  • cookies() and headers() in Server Components make the route dynamic — cache results when possible
  • Always handle loading and error states with Suspense + error.tsx

Individual skills in this repo

This repo contains 4 individual skills — each has its own dedicated page.

Verwandte Skills