Next.js Expert
Overview
Advanced expertise in Next.js — from App Router and Server Components to full-stack deployment on Vercel and self-hosted environments. Covers both the modern App Router and legacy Pages Router patterns.
1. App Router (Next.js 13+)
app/directory structure: layouts, pages, loading, error, not-found- Nested layouts with
layout.tsx— shared UI without re-rendering - Route groups
(group)/for organizing without affecting URL - Dynamic segments:
[slug],[...catchAll],[[...optionalCatchAll]] - Parallel routes
@slotand intercepting routes(.)route page.tsx,layout.tsx,loading.tsx,error.tsx,not-found.tsx,template.tsxroute.tsAPI Route Handlers (GET, POST, PUT, DELETE, PATCH)- Metadata API:
export const metadata,generateMetadata()
2. Server Components & Client Components
- Server Components (default): no state, no hooks, async, direct DB/API access
- Client Components:
"use client"directive, useState/useEffect allowed - Composition patterns: wrap Client Components inside Server Components
- Passing Server Component output as
childrento Client Components Suspenseboundaries for streaming and partial hydration- Server-only imports:
server-onlypackage to prevent leaking use()hook for promise-based data in Client Components
3. Data Fetching
fetch()with Next.js cache extensions:cache: 'force-cache'(SSG),cache: 'no-store'(SSR)next: { revalidate: 60 }for ISR (Incremental Static Regeneration)next: { tags: ['tag'] }for tag-based revalidationrevalidatePath()andrevalidateTag()fromnext/cachegenerateStaticParams()for static path generation- Parallel data fetching with
Promise.all() - Request memoization — same
fetch()deduped within a render
4. Server Actions
"use server"directive — in file or inline in Server Components- Form actions:
<form action={serverAction}> useFormState/useActionState(React 19) for progressive enhancementuseFormStatusfor pending UI states- Revalidating after mutations:
revalidatePath(),revalidateTag() - Redirecting:
redirect()fromnext/navigation - Error handling:
try/catch, returning error state objects next-safe-actionfor type-safe server actions with Zod validation
5. Routing & Navigation
useRouter()fromnext/navigation(App Router)usePathname(),useSearchParams(),useParams()<Link>component — prefetching,replace,scroll- Programmatic navigation:
router.push(),router.replace(),router.back() - Middleware:
middleware.tsat root — runs on Edge, matchers config NextResponse.redirect(),NextResponse.rewrite(),NextResponse.next()- Internationalization (i18n) routing patterns
6. Pages Router (Legacy / Still Supported)
pages/directory: file-based routinggetStaticProps,getStaticPathsfor SSGgetServerSidePropsfor SSRgetInitialProps(avoid — disables automatic static optimization)pages/api/for API routes_app.tsx,_document.tsxcustomizationnext/router(useRouter) for Pages Router
7. Styling
- CSS Modules:
styles.module.css— scoped class names - Tailwind CSS integration with
tailwind.config.ts next/font— self-hosted Google Fonts, zero layout shift- CSS-in-JS with App Router: only compatible libs (Linaria, Panda CSS, StyleX)
clsx/cnutility for conditional classes- Global styles in
app/globals.cssorpages/_app.tsx
8. Images & Media
next/image— lazy loading, automatic WebP, blur placeholderfillprop for responsive images inside positioned containerssizesprop for responsive breakpoints- Remote image domains in
next.config.js→images.remotePatterns next/videopatterns and self-hosted media- Static assets in
public/directory
9. Authentication
- NextAuth.js v5 (Auth.js): providers, session, callbacks, middleware
- JWT vs database sessions configuration
auth()helper in Server Components and API routes- Protecting routes with middleware matchers
- Custom credentials provider with Zod validation
- OAuth providers: Google, GitHub, Discord setup
10. Performance & Optimization
next/dynamicfor lazy-loaded Client Components (ssr: falseoption)- Bundle analyzer:
@next/bundle-analyzer React.cache()for server-side request memoization- Streaming with Suspense — progressive rendering
prefetchon<Link>— disabled for authenticated routes- Static vs dynamic rendering decision tree
- Partial Prerendering (PPR) — experimental Next.js 14+
unstable_cachefor caching arbitrary async functions
11. Configuration (next.config.js / next.config.ts)
import type { NextConfig } from 'next'
const config: NextConfig = {
experimental: {
ppr: true, // Partial Prerendering
serverActions: { allowedOrigins: ['...'] },
},
images: {
remotePatterns: [{ hostname: 'example.com' }],
},
redirects: async () => [
{ source: '/old', destination: '/new', permanent: true },
],
headers: async () => [...],
env: { CUSTOM_VAR: process.env.CUSTOM_VAR },
turbopack: {}, // Turbopack (replaces Webpack)
}
export default config
12. Deployment
- Vercel: zero-config, Edge Functions, Analytics, KV, Blob, Postgres
- Self-hosted Node.js:
next build→next start, requires Node 18+ - Docker: multi-stage build with
output: 'standalone'in next.config - Static Export:
output: 'export'for pure static sites (no SSR) - Environment variables:
.env.local,.env.production,NEXT_PUBLIC_prefix for client - Edge Runtime:
export const runtime = 'edge'in route handlers
13. Testing
- Jest + React Testing Library for unit/integration tests
- Playwright or Cypress for E2E tests
jest.config.tswithnext/jesttransformer- Mocking
next/navigationhooks in tests @testing-library/user-eventfor user interaction simulation
14. TypeScript Patterns
// Page props with params and searchParams
type Props = {
params: Promise<{ slug: string }>
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}
// Route Handler
import { NextRequest, NextResponse } from 'next/server'
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return NextResponse.json({ id })
}
Core Competency Summary
- Build full-stack apps with App Router, Server Components, and Server Actions
- Implement authentication with NextAuth.js v5
- Optimize for Core Web Vitals and static/dynamic rendering balance
- Deploy on Vercel or self-host with Docker
- Write type-safe Next.js with TypeScript and Zod validation