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
type ButtonProps = {
variant: 'primary' | 'secondary' | 'ghost'
size?: 'sm' | 'md' | 'lg'
isLoading?: boolean
onClick?: () => void
children: React.ReactNode
}
type ApiResult<T> =
| { success: true; data: T }
| { success: false; error: string; code: number }
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>
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
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} />
}
'use client'
import { useState, useTransition } from 'react'
export function InteractiveForm() {
const [isPending, startTransition] = useTransition()
}
Server Actions
'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 }
}
'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
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} />
}
import { Suspense } from 'react'
export default function Page() {
return (
<>
<StaticHeader />
<Suspense fallback={<Skeleton />}>
<SlowDataComponent /> {/* Streams in when ready */}
</Suspense>
</>
)
}
export const revalidate = 3600
import { revalidatePath, revalidateTag } from 'next/cache'
revalidatePath('/products')
revalidateTag('products')
const data = await fetch('https://api.example.com/products', {
next: { tags: ['products'], revalidate: 3600 }
})
Middleware
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))
}
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)
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()
}
Authentication (NextAuth v5 / Auth.js)
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
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' }
)
)
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
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 }],
},
}
}
import Image from 'next/image'
<Image src={url} alt={alt} width={800} height={600} priority sizes="(max-width: 768px) 100vw, 50vw" />
import { Inter, Geist_Mono } from 'next/font/google'
const inter = Inter({ subsets: ['latin'], display: 'swap' })
import dynamic from 'next/dynamic'
const HeavyChart = dynamic(() => import('@/components/HeavyChart'), {
loading: () => <Skeleton />,
ssr: false,
})
Environment Variables
DATABASE_URL="postgresql://..."
NEXTAUTH_SECRET="..."
NEXTAUTH_URL="http://localhost:3000"
DATABASE_URL="postgresql://user:pass@localhost:5432/mydb"
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
'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>
)
}
export default function NotFound() {
return <div>404 - Page not found</div>
}
'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)
| Category | Library | Notes |
|---|
| ORM | Prisma or Drizzle | Prisma for DX, Drizzle for performance |
| Auth | Auth.js v5 (NextAuth) | Or Clerk for managed auth |
| Validation | Zod | Use everywhere |
| UI | shadcn/ui + Tailwind CSS | Copy-paste component model |
| State | Zustand + TanStack Query | Client + server state |
| Forms | React Hook Form + Zod | With Server Actions fallback |
| Email | Resend + React Email | |
| Payments | Stripe | See payment-gateway skill |
| Env | @t3-oss/env-nextjs | Type-safe env vars |
| Error tracking | Sentry | |
| Analytics | Vercel 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