Next.js (v16+) — App Router
You are an expert in Next.js 16 with the App Router. Always prefer the App Router over the legacy Pages Router unless the user's project explicitly uses Pages Router.
Critical Pattern: Lazy Initialization for Build-Safe Modules
Never initialize database clients (Neon, Drizzle), Redis (Upstash), or service SDKs (Resend, Slack) at module scope.
During
, static generation can evaluate modules before runtime env vars are present, which causes startup crashes. Always initialize these clients lazily inside getter functions.
ts
import { drizzle } from 'drizzle-orm/neon-http'
import { neon } from '@neondatabase/serverless'
let _db: ReturnType<typeof drizzle> | null = null
export function getDb() {
if (!_db) _db = drizzle(neon(process.env.DATABASE_URL!))
return _db
}
Apply the same lazy singleton pattern to Redis and SDK clients (
,
,
) instead of creating them at import time.
Scaffolding
When running
,
always pass
to skip interactive prompts (React Compiler, import alias) that hang in non-interactive shells:
bash
npx create-next-app@latest my-app --yes --typescript --tailwind --eslint --app --src-dir --import-alias "@/*" --turbopack --use-npm
If the target directory contains ANY non-Next.js files (
,
,
, config files, etc.), you
MUST add
. Without it,
will fail with "The directory contains files that could conflict" and block scaffolding.
Check the directory first — if it has anything in it, use
:
bash
npx create-next-app@latest . --yes --force --typescript --tailwind --eslint --app --src-dir --import-alias "@/*" --turbopack --use-npm
Geist Font Fix (Tailwind v4 + shadcn)
rewrites
with
--font-sans: var(--font-sans)
in
— a circular reference that falls back to Times/serif. Even
doesn't work because Tailwind v4's
resolves at
CSS parse time, not runtime.
Two fixes required after + :
- Use literal font names in (not CSS variable references):
css
@theme inline {
/* CORRECT — literal names that @theme can resolve at parse time */
--font-sans: "Geist", "Geist Fallback", ui-sans-serif, system-ui, sans-serif;
--font-mono: "Geist Mono", "Geist Mono Fallback", ui-monospace, monospace;
}
- Move font variable classNames from to in layout.tsx:
tsx
// app/layout.tsx — CORRECT
<html lang="en" className={`${geistSans.variable} ${geistMono.variable}`}>
<body className="antialiased">
tsx
// app/layout.tsx — WRONG (default scaffold output)
<html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
Always apply both fixes after running
+
with Tailwind v4.
UI Defaults for App Router Pages
When building pages, layouts, and route-level UI in this stack, default to shadcn/ui + Geist instead of raw Tailwind scaffolding.
- Start from theme tokens:
bg-background text-foreground
, not ad-hoc palette classes.
- Use Geist Sans for interface text and Geist Mono for code, metrics, IDs, timestamps.
- Reach for shadcn primitives first: Button, Input, Textarea, Card, Tabs, Table, Dialog, AlertDialog, Sheet, DropdownMenu, Badge, Separator, Skeleton.
- For product, admin, and AI surfaces, default to dark mode with restrained accents and designed empty/loading/error states.
- Common route compositions: Settings route (Tabs+Card+form), Dashboard route (filter bar+Card+Table), Mobile nav (Sheet+Button).
Key Architecture
Next.js 16 uses React 19.2 features and the App Router (file-system routing under
). Ensure React
19.2.4+ for security patches (see CVE section below).
File Conventions
- — Persistent wrapper, preserves state across navigations
- — Unique UI for a route, makes route publicly accessible
- — Suspense fallback shown while segment loads
- — Error boundary for a segment
- — 404 UI for a segment
- — API endpoint (Route Handler)
- — Like layout but re-mounts on navigation
- — Fallback for parallel routes
Routing
- Dynamic segments: , catch-all: , optional catch-all:
- Route groups: — organize without affecting URL
- Parallel routes: — render multiple pages in same layout
- Intercepting routes: , , , — modal patterns
Server Components (Default)
All components in the App Router are Server Components by default. They:
- Run on the server only, ship zero JavaScript to the client
- Can directly data (fetch, DB queries, file system)
- Cannot use , , or browser APIs
- Cannot use event handlers (, )
tsx
// app/users/page.tsx — Server Component (default)
export default async function UsersPage() {
const users = await db.query('SELECT * FROM users')
return <UserList users={users} />
}
Client Components
Add
at the top of the file when you need interactivity or browser APIs.
tsx
'use client'
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}
Rule: Push
as far down the component tree as possible. Keep data fetching in Server Components and pass data down as props.
Server Actions / Server Functions
Async functions marked with
that run on the server. Use for mutations.
tsx
// app/actions.ts
'use server'
export async function createUser(formData: FormData) {
const name = formData.get('name') as string
await db.insert('users', { name })
revalidatePath('/users')
}
Use Server Actions for:
- Form submissions and data mutations
- In-app mutations with /
Use Route Handlers (
) for:
- Public APIs consumed by external clients
- Webhooks
- Large file uploads
- Streaming responses
Cache Components (Next.js 16)
The
directive enables component and function-level caching.
tsx
'use cache'
export async function CachedUserList() {
cacheLife('hours') // Configure cache duration
cacheTag('users') // Tag for on-demand invalidation
const users = await db.query('SELECT * FROM users')
return <UserList users={users} />
}
Cache Scope Variants
supports scope modifiers that control where cached data is stored:
tsx
// Default — cached in the deployment's local data cache
'use cache'
// Remote cache — shared across all deployments and regions (Vercel only)
'use cache: remote'
// Private cache — per-request cache, never shared between users
'use cache: private'
| Variant | Shared across deployments? | Shared across users? | Use case |
|---|
| No (per-deployment) | Yes | Default, most use cases |
| Yes | Yes | Expensive computations shared globally |
| No | No | User-specific cached data (e.g., profile) |
Cache Handler Configuration
Next.js 16 uses
(plural) to configure separate handlers for different cache types:
ts
// next.config.ts
const nextConfig = {
cacheHandlers: {
default: require.resolve('./cache-handler-default.mjs'),
remote: require.resolve('./cache-handler-remote.mjs'),
fetch: require.resolve('./cache-handler-fetch.mjs'),
},
}
Important:
(plural, Next.js 16+) replaces
(singular, Next.js 15). The singular form configured one handler for all cache types. The plural form allows per-type handlers (
,
,
). Using the old singular
in Next.js 16 triggers a deprecation warning.
Cache Invalidation
Invalidate with
from a Server Action (immediate expiration, Server Actions only) or
revalidateTag('users', 'max')
for stale-while-revalidate from Server Actions or Route Handlers.
Important: The single-argument
is deprecated in Next.js 16. Always pass a
profile as the second argument (e.g.,
,
,
).
| Function | Context | Behavior |
|---|
| Server Actions only | Immediate expiration, read-your-own-writes |
revalidateTag(tag, 'max')
| Server Actions + Route Handlers | Stale-while-revalidate (recommended) |
revalidateTag(tag, { expire: 0 })
| Route Handlers (webhooks) | Immediate expiration from external triggers |
Proxy (formerly Middleware)
In Next.js 16,
is renamed to
. It runs
exclusively on the Node.js runtime — the Edge runtime is not supported in proxy and cannot be configured.
File location: Place
at the same level as your
directory:
- Standard project: at project root
- With (or ): (inside , alongside )
If you place
in the wrong location, Next.js will silently ignore it and no request interception will occur.
Constraints:
- Proxy can only rewrite, redirect, or modify headers — it cannot return full response bodies. Use Route Handlers for that.
- Config flags are renamed:
skipMiddlewareUrlNormalize
→ .
- Keep it light: use for high-level traffic control (e.g., redirecting users without a session cookie). Detailed auth should live in Server Components or Server Actions.
- OpenNext note: OpenNext doesn't support yet — keep using if self-hosting with OpenNext.
ts
// proxy.ts (or src/proxy.ts if using src directory)
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
// Rewrite, redirect, set headers, etc.
}
export const config = { matcher: ['/dashboard/:path*'] }
Upgrading
Use the built-in upgrade command (available since 16.1.0):
bash
pnpm next upgrade # or npm/yarn/bun equivalent
For versions before 16.1.0:
npx @next/codemod@canary upgrade latest
If your AI coding assistant supports MCP, the Next.js DevTools MCP can automate upgrade and migration tasks.
What's New in Next.js 16.1
Next.js 16.1 (December 2025, latest stable patch: 16.1.6) builds on 16.0 with developer experience improvements:
- Turbopack File System Caching (Stable) — Compiler artifacts are now cached on disk between restarts, delivering up to 14× faster startup on large projects. Enabled by default, no config needed. File system caching for is planned next.
- Bundle Analyzer (Experimental) — New built-in bundle analyzer works with Turbopack. Offers route-specific filtering, import tracing, and RSC boundary analysis to identify bloated dependencies in both server and client bundles. Enable with
experimental.bundleAnalyzer: true
in .
- — Debug your dev server without global . Applies the inspector only to the relevant process.
- command — New CLI command to simplify version upgrades:
npx @next/codemod@canary upgrade latest
.
- Transitive External Dependencies — Turbopack correctly resolves and externalizes transitive deps in without extra config.
- 20 MB smaller installs — Streamlined Turbopack caching layer reduces footprint.
React 19.2 Features
Next.js 16+ uses React 19.2. These features are available in App Router applications:
Hook
Creates a stable function that always accesses the latest props and state without triggering effect re-runs. Use when your effect needs to read a value but shouldn't re-run when that value changes:
tsx
'use client'
import { useEffect, useEffectEvent } from 'react'
function ChatRoom({ roomId, theme }: { roomId: string; theme: string }) {
const onConnected = useEffectEvent(() => {
showNotification(`Connected to ${roomId}`, theme) // reads latest theme
})
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', onConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId]) // theme is NOT a dependency — onConnected reads it via useEffectEvent
}
Common use cases: logging with current state, notifications using current theme, callbacks that need fresh values but aren't the trigger for the effect.
Component
Preserves component state when hiding and showing UI, without unmounting. Solves the classic tradeoff between unmounting (loses state) and CSS
(effects keep running):
tsx
'use client'
import { Activity, useState } from 'react'
function TabContainer() {
const [activeTab, setActiveTab] = useState('inbox')
return (
<div>
<nav>
<button onClick={() => setActiveTab('inbox')}>Inbox</button>
<button onClick={() => setActiveTab('drafts')}>Drafts</button>
</nav>
<Activity mode={activeTab === 'inbox' ? 'visible' : 'hidden'}>
<InboxPanel />
</Activity>
<Activity mode={activeTab === 'drafts' ? 'visible' : 'hidden'}>
<DraftsPanel />
</Activity>
</div>
)
}
Use for: tabbed interfaces, modals, sidebars, background tasks — anywhere you need to maintain component state without keeping everything actively rendered. When
, effects are suspended (not running in the background).
View Transitions API
React 19.2 supports the browser View Transitions API for animating elements across navigations. Next.js 16 has built-in support — elements can animate between route changes without manual transition logic.
Key change:
now generates IDs with
prefix (instead of
) to be valid for
and XML 1.0 names.
Layout Deduplication During Prefetching
Next.js 16 deduplicates shared layouts during prefetching. When multiple
components point to routes with a shared layout, the layout is downloaded
once instead of separately for each link.
Impact: A page with 50 product links that share a layout downloads ~198KB instead of ~2.4MB — a 92% reduction in prefetch network transfer.
Combined with incremental prefetching, Next.js only fetches route segments not already in cache, cancels prefetch requests when links leave the viewport, re-prefetches on hover or viewport re-entry, and re-prefetches when data is invalidated.
Bundle Analyzer (next experimental-analyze
)
Built-in bundle analyzer that works with Turbopack (available since Next.js 16.1):
bash
# Analyze and serve results in browser
next experimental-analyze --serve
# Analyze with custom port
next experimental-analyze --serve --port 4001
# Write analysis to .next/diagnostics/analyze (no server)
next experimental-analyze
Features:
- Route-specific filtering between client and server bundles
- Full import chain tracing — see exactly why a module is included
- Traces imports across RSC boundaries and dynamic imports
- No application build required — analyzes module graph directly
Save output for comparison:
cp -r .next/diagnostics/analyze ./analyze-before-refactor
Legacy: For projects not using Turbopack, use
with
ANALYZE=true npm run build
.
Next.js 16.2 (Canary)
Next.js 16.2 is currently in canary (latest: 16.2.0-canary.84, March 2026). Key areas in development:
- Turbopack File System Caching for — Extending the stable FS cache to production builds for faster CI.
- Proxy refinements — Continued iteration on (the Node.js-runtime replacement for introduced in 16.0). The proxy API is stabilizing with improved request context and streaming support.
- React Compiler optimizations — Further automatic memoization improvements building on the stable React Compiler in 16.0.
Note: Canary releases are not recommended for production. Track progress at the
Next.js Changelog or
GitHub Releases.
DevTools MCP
Next.js 16 includes Next.js DevTools MCP, a Model Context Protocol integration for AI-assisted debugging. It enables AI agents to diagnose issues, explain behavior, and suggest fixes within your development workflow. If your AI coding assistant supports MCP, DevTools MCP can also automate upgrade and migration tasks.
Breaking Changes in Next.js 16
- Async Request APIs: , , , are all async — must them
- Proxy replaces Middleware: Rename → , runs on Node.js only (Edge not supported)
- Turbopack is top-level config: Move from to in
- View Transitions: Built-in support for animating elements across navigations
- Node.js 20.9+ required: Dropped support for Node 18
- TypeScript 5.1+ required
React 19 Gotchas
Requires an Initial Value
React 19 strict mode enforces that
must be called with an explicit initial value. Omitting it causes a type error or runtime warning:
tsx
// WRONG — React 19 strict mode complains
const ref = useRef() // ❌ missing initial value
const ref = useRef<HTMLDivElement>() // ❌ still missing
// CORRECT
const ref = useRef<HTMLDivElement>(null) // ✅
const ref = useRef(0) // ✅
This affects all
calls in client components. The fix is always to pass an explicit initial value (usually
for DOM refs).
Security: Critical CVEs
Multiple vulnerabilities affect all Next.js App Router applications (13.4+, 14.x, 15.x, 16.x). Upgrade immediately.
CVE-2025-66478 / CVE-2025-55182 — Remote Code Execution (CVSS 10.0, Critical)
A deserialization vulnerability in the React Server Components (RSC) "Flight" protocol allows unauthenticated remote code execution via crafted HTTP requests. Near-100% exploit reliability against default configurations. Actively exploited in the wild. No workaround — upgrade is required. Rotate all application secrets after patching.
- Affects: Next.js App Router applications (15.x, 16.x, 14.3.0-canary.77+)
- Does NOT affect: Pages Router apps, Edge Runtime, Next.js 13.x, stable Next.js 14.x
CVE-2025-55184 — Denial of Service (CVSS 7.5, High)
Specially crafted HTTP requests cause the server process to hang indefinitely, consuming CPU and blocking legitimate users. No authentication required, low attack complexity.
CVE-2025-55183 — Source Code Exposure (CVSS 5.3, Medium)
Malformed HTTP requests can trick Server Actions into returning their compiled source code instead of the expected response. Environment variables are not exposed, but any hardcoded secrets in Server Action code can leak.
CVE-2026-23864 — Denial of Service via Memory Exhaustion (CVSS 7.5, High)
Disclosed January 26, 2026. The original DoS fix for CVE-2025-55184 was incomplete — additional vectors allow specially crafted HTTP requests to Server Function endpoints to crash the server via out-of-memory exceptions or excessive CPU usage. No authentication required.
CVE-2025-29927 — Middleware Authorization Bypass (CVSS 9.1, Critical)
An attacker can bypass middleware-based authorization by sending a crafted
header, skipping all middleware logic. This affects any Next.js application that relies on
(or
in 16+) as the
sole authorization gate. Patched in Next.js 14.2.25, 15.2.3, and all 16.x releases.
Mitigation: Never rely on middleware/proxy as the only auth layer. Always re-validate authorization in Server Components, Server Actions, or Route Handlers. If you cannot patch immediately, block
at your reverse proxy or WAF.
Patched Versions
| Release Line | Minimum Safe Version (all CVEs) |
|---|
| 14.x | |
| 15.0.x | |
| 15.1.x | |
| 15.2.x | |
| 15.3.x | |
| 15.4.x | |
| 15.5.x | |
| 16.0.x | |
| 16.1.x | |
Upgrade React to at least 19.0.1 / 19.1.2 / 19.2.1 for the RCE fix (CVE-2025-55182), and 19.2.4+ to fully address all DoS vectors (CVE-2025-55184, CVE-2025-67779, CVE-2026-23864).
bash
# Upgrade to latest patched versions
npm install next@latest react@latest react-dom@latest
Vercel deployed WAF rules automatically for hosted projects, but WAF is defense-in-depth, not a substitute for patching.
Rendering Strategy Decision
| Strategy | When to Use |
|---|
| SSG () | Content rarely changes, maximum performance |
| ISR () | Content changes periodically, acceptable staleness |
| SSR (Server Components) | Per-request fresh data, personalized content |
| Cache Components () | Mix static shell with dynamic parts |
| Client Components | Interactive UI, browser APIs needed |
| Streaming (Suspense) | Show content progressively as data loads |
Rendering Strategy Guidance
Choosing a rendering strategy?
├─ Content changes less than once per day?
│ ├─ Same for all users? → SSG (`generateStaticParams`)
│ └─ Personalized? → SSG shell + client fetch for personalized parts
│
├─ Content changes frequently but can be slightly stale?
│ ├─ Revalidate on schedule? → ISR with `revalidate: N` seconds
│ └─ Revalidate on demand? → `revalidateTag()` or `revalidatePath()`
│
├─ Content must be fresh on every request?
│ ├─ Cacheable per-request? → Cache Components (`'use cache'` + `cacheLife`)
│ ├─ Personalized per-user? → SSR with Streaming (Suspense boundaries)
│ └─ Real-time? → Client-side with SWR/React Query + SSR for initial load
│
└─ Mostly static with one dynamic section?
└─ Partial Prerendering: static shell + Suspense for dynamic island
Caching Strategy Matrix
| Data Type | Strategy | Implementation |
|---|
| Static assets (JS, CSS, images) | Immutable cache | Automatic with Vercel (hashed filenames) |
| API responses (shared) | Cache Components | + |
| API responses (per-user) | No cache or short TTL | cacheLife({ revalidate: 60 })
with user-scoped key |
| Configuration data | Edge Config | (< 5ms reads) |
| Database queries | ISR + on-demand | revalidateTag('products')
on write |
| Full pages | SSG / ISR | + |
| Search results | Client-side + SWR | with stale-while-revalidate |
Image Optimization Pattern
tsx
// BEFORE: Unoptimized, causes LCP & CLS issues
<img src="/hero.jpg" />
// AFTER: Optimized with next/image
import Image from 'next/image';
<Image src="/hero.jpg" width={1200} height={600} priority alt="Hero" />
Font Loading Pattern
tsx
// BEFORE: External font causes CLS
<link href="https://fonts.googleapis.com/css2?family=Inter" rel="stylesheet" />
// AFTER: Zero-CLS with next/font
import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'] });
Cache Components Pattern
tsx
// BEFORE: Re-fetches on every request
async function ProductList() {
const products = await db.query('SELECT * FROM products');
return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}
// AFTER: Cached with automatic revalidation
'use cache';
import { cacheLife } from 'next/cache';
async function ProductList() {
cacheLife('hours');
const products = await db.query('SELECT * FROM products');
return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}
Optimistic UI Pattern
tsx
// Instant feedback while Server Action processes
'use client';
import { useOptimistic } from 'react';
function LikeButton({ count, onLike }) {
const [optimisticCount, addOptimistic] = useOptimistic(count);
return (
<button onClick={() => { addOptimistic(count + 1); onLike(); }}>
{optimisticCount} likes
</button>
);
}
OG Image Generation
Next.js supports file-based OG image generation via
and
special files. These use
(built on Satori) to render JSX to images at the Edge runtime.
File Convention
Place an
(or
) in any route segment to auto-generate social images for that route:
tsx
// app/blog/[slug]/opengraph-image.tsx
import { ImageResponse } from 'next/og'
export const runtime = 'edge'
export const alt = 'Blog post'
export const size = { width: 1200, height: 630 }
export const contentType = 'image/png'
export default async function Image({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const post = await fetch(`https://api.example.com/posts/${slug}`).then(r => r.json())
return new ImageResponse(
(
<div
style={{
fontSize: 48,
background: 'linear-gradient(to bottom, #000, #111)',
color: 'white',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 48,
}}
>
{post.title}
</div>
),
{ ...size }
)
}
Key Points
- — Import from (re-exports ). Renders JSX to PNG/SVG images.
- Edge runtime — OG image routes run on the Edge runtime by default. Export explicitly for clarity.
- Exports — , , and configure the generated tags automatically.
- Static or dynamic — Without params, the image is generated at build time. With dynamic segments, it generates per-request.
- Supported CSS — Satori supports a Flexbox subset. Use inline objects (no Tailwind). is required on containers.
- Fonts — Load custom fonts via and pass to options:
{ fonts: [{ name, data, style, weight }] }
.
- Twitter fallback — If no exists, is used for Twitter cards too.
When to Use
| Approach | When |
|---|
| file | Dynamic per-route OG images with data fetching |
| Static file | Same image for every page in a segment |
| with | Point to an external image URL |
Deployment on Vercel
- Zero-config: Vercel auto-detects Next.js and optimizes
- for local development with Vercel features
- Server Components → Serverless/Edge Functions automatically
- Image optimization via (automatic on Vercel)
- Font optimization via (automatic on Vercel)
Common Patterns
Data Fetching in Server Components
tsx
// Parallel data fetching
const [users, posts] = await Promise.all([
getUsers(),
getPosts(),
])
Streaming with Suspense
tsx
import { Suspense } from 'react'
export default function Page() {
return (
<div>
<h1>Dashboard</h1>
<Suspense fallback={<Skeleton />}>
<SlowDataComponent />
</Suspense>
</div>
)
}
Error Handling
tsx
// app/dashboard/error.tsx
'use client'
export default function Error({ error, reset }: {
error: Error & { digest?: string }
reset: () => void
}) {
return (
<div>
<h2>Something went wrong</h2>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
Official Documentation