Next.js Best Practices: App Router Guide for Routing, Data Fetching, Caching, Server Actions, Performance and Security
A practical, opinionated Next.js best practices guide for developers building with the App Router in Next.js 16. It covers project structure, routing, Server and Client Components, data fetching, Cache Components ("use cache"), revalidation, Server Actions, Proxy (formerly middleware), SEO metadata, performance and security, with copy-paste examples and a production checklist. It is written for React developers moving to the App Router and for teams that want one shared set of conventions.
Last reviewed: December 2026, against the Next.js 16.x docs (16.4 was the current minor at review time). APIs that changed recently are called out with the version that introduced them. When in doubt, the official Next.js docs win.
Table of Contents
- 1. The mental model in five sentences
- 2. Project structure
- 3. Routing patterns
- 4. Server Components and Client Components
- 5. Data fetching
- 6. Caching with Cache Components
- 7. Revalidation
- 8. Server Actions and mutations
- 9. Route Handlers
- 10. Proxy (formerly middleware)
- 11. Loading, errors and not-found
- 12. Metadata and SEO
- 13. Performance
- 14. Security
- 15. Environment variables and configuration
- 16. Testing
- 17. Deployment and self-hosting
- 18. Common mistakes and fixes
- 19. Production checklist
- 20. Further reading
- 21. Rendering and data strategies compared
- 22. Choosing libraries
- 23. FAQ
- 24. Where to go next
- Contributing
- More free resources
1. The mental model in five sentences
- Everything in
app/is a Server Component by default. It runs on the server, can beasync, can read databases and secrets, and ships zero JavaScript for itself. "use client"marks a boundary, not a component. The file with the directive and everything it imports become part of the client bundle. Keep boundaries small and push them down to the leaves.- Rendering produces a static shell plus streamed holes. With Cache Components enabled, anything that can finish at build time (static markup,
"use cache"results) goes in the prerendered shell. Anything that needs the request (cookies, headers, search params, uncached fetches) streams in behind a<Suspense>fallback. - Mutations go through Server Actions (or Route Handlers), then you tell the cache what changed with
updateTag,revalidateTagorrevalidatePath. - Every Server Action and Route Handler is a public HTTP endpoint. Authenticate and authorize inside each one, never only in Proxy or in the UI.
If you remember only these five rules, most App Router bugs disappear.
2. Project structure
Next.js does not force a layout, but a predictable one makes code review and onboarding easier. A structure that scales well:
.
├── app/
│ ├── (marketing)/ # route group: does not affect the URL
│ │ ├── layout.tsx
│ │ ├── page.tsx # "/"
│ │ └── pricing/page.tsx # "/pricing"
│ ├── (app)/
│ │ ├── layout.tsx # authenticated shell
│ │ ├── dashboard/
│ │ │ ├── page.tsx
│ │ │ ├── loading.tsx
│ │ │ ├── error.tsx
│ │ │ └── _components/ # private folder: never becomes a route
│ │ └── settings/page.tsx
│ ├── api/
│ │ └── webhooks/stripe/route.ts
│ ├── layout.tsx # root layout (<html>, <body>)
│ ├── not-found.tsx
│ ├── global-error.tsx
│ ├── sitemap.ts
│ └── robots.ts
├── components/ # shared UI used by many routes
├── lib/
│ ├── dal.ts # data access layer (server-only)
│ ├── auth.ts
│ └── validation.ts
├── proxy.ts # optional, at the same level as app/
├── next.config.ts
└── tsconfig.json
Guidelines:
- Colocate route-only code in a private folder (
_components,_lib) next to the route that uses it. The underscore prefix opts the folder out of routing. - Use route groups
(name)to give different sections different layouts (marketing vs. app) without changing URLs. - Keep
lib/server-first. Putimport 'server-only'at the top of modules that touch the database or secrets so an accidental client import fails the build. - One root layout per app unless you deliberately need several (multiple root layouts cause full page loads when crossing between them).
- Use the
src/folder or not, but be consistent. If you use it,proxy.tsandinstrumentation.tsmove intosrc/too.
Special files cheat sheet
| File | Purpose | Server or Client |
|---|---|---|
layout.tsx |
Shared UI that persists across navigations | Server by default |
page.tsx |
The UI for a route; makes the segment publicly routable | Server by default |
loading.tsx |
Instant loading UI, wraps page in <Suspense> |
Server by default |
error.tsx |
Error boundary for the segment | Must be Client |
global-error.tsx |
Error boundary for the root layout; renders its own <html> |
Must be Client |
not-found.tsx |
UI for notFound() and unmatched URLs |
Server by default |
template.tsx |
Like layout, but remounts on every navigation | Server by default |
default.tsx |
Fallback for parallel route slots | Server by default |
route.ts |
HTTP handler (GET, POST, …) instead of a page | Server |
proxy.ts |
Runs before routes are rendered | Server (Node.js runtime) |
3. Routing patterns
Dynamic segments
| Folder | Matches | params |
|---|---|---|
app/blog/[slug]/page.tsx |
/blog/hello |
{ slug: 'hello' } |
app/shop/[...parts]/page.tsx |
/shop/a/b |
{ parts: ['a', 'b'] } |
app/docs/[[...parts]]/page.tsx |
/docs and /docs/a/b |
{ parts: undefined } or { parts: ['a','b'] } |
params and searchParams are Promises. Await them (in Server Components) or unwrap them with React.use() (in Client Components). Next.js generates global helper types so you do not have to hand-write prop types:
// app/blog/[slug]/page.tsx
export default async function Page(props: PageProps<'/blog/[slug]'>) {
const { slug } = await props.params
const post = await getPost(slug)
return <article>{post.title}</article>
}
LayoutProps<'/route'> and RouteContext<'/route'> (for Route Handlers) work the same way. Run next dev, next build or next typegen to generate them.
Prerender known params
export async function generateStaticParams() {
const posts = await getAllPostSlugs()
return posts.map((slug) => ({ slug }))
}
Listed params are prerendered at build time. Unknown params are rendered on first visit and then cached (incremental static regeneration).
Linking and navigation
- Use
<Link href="...">for internal links. It prefetches routes in the viewport and does client-side transitions. - Use
useRouter()fromnext/navigation(notnext/router) for imperative navigation in Client Components. - Use
redirect()fromnext/navigationin Server Components, Server Actions and Route Handlers. It throws, so do not wrap it intry/catch(or rethrow it). - Use
permanentRedirect()for 308 redirects when a URL has moved for good. - Static, known redirects belong in
next.config.tsredirects(), not in code.
Parallel and intercepting routes
Parallel routes (@slot folders) render several pages in one layout, for example a dashboard with independently loading panels:
app/dashboard/
├── layout.tsx // receives { children, analytics, team }
├── page.tsx
├── @analytics/page.tsx
├── @analytics/default.tsx
└── @team/page.tsx
Intercepting routes ((.)photo/[id]) show a route inside the current layout, the classic “open photo as modal, but a full page on refresh” pattern. Always add default.tsx to slots so hard refreshes do not 404.
Typed routes
Enable compile-time checking of href strings:
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
typedRoutes: true,
}
export default nextConfig
Typos in <Link href> and router.push() now fail type checking.
4. Server Components and Client Components
When to use which
| Need | Use |
|---|---|
| Fetch data, read DB, use secrets | Server Component |
| Large dependencies that only format or render (markdown, syntax highlighting, date libs) | Server Component |
useState, useEffect, useReducer, refs |
Client Component |
Event handlers (onClick, onChange) |
Client Component |
Browser APIs (localStorage, window, IntersectionObserver) |
Client Component |
| Context providers | Client Component (rendered from a Server layout) |
Push "use client" to the leaves
Bad: making a whole page a Client Component because one button needs state.
// app/product/[id]/page.tsx (avoid)
'use client'
export default function Page() { /* everything is now client JS */ }
Good: keep the page on the server and make only the interactive part a Client Component.
// app/product/[id]/page.tsx
import { AddToCart } from './_components/add-to-cart'
export default async function Page(props: PageProps<'/product/[id]'>) {
const { id } = await props.params
const product = await getProduct(id)
return (
<main>
<h1>{product.name}</h1>
<p>{product.description}</p>
<AddToCart productId={product.id} />
</main>
)
}
// app/product/[id]/_components/add-to-cart.tsx
'use client'
import { useState } from 'react'
export function AddToCart({ productId }: { productId: string }) {
const [qty, setQty] = useState(1)
return (
<button onClick={() => setQty((q) => q + 1)}>
Add {qty} of {productId}
</button>
)
}
Pass Server Components as children
A Client Component cannot import a Server Component, but it can render one passed as a prop:
// components/collapsible.tsx
'use client'
import { useState, type ReactNode } from 'react'
export function Collapsible({ title, children }: { title: string; children: ReactNode }) {
const [open, setOpen] = useState(false)
return (
<section>
<button onClick={() => setOpen(!open)}>{title}</button>
{open && children}
</section>
)
}
// app/page.tsx (Server Component)
<Collapsible title="Comments">
<Comments /> {/* still a Server Component, fetched on the server */}
</Collapsible>
Props crossing the boundary must be serializable
Allowed: strings, numbers, booleans, null, plain objects and arrays, Date, Map, Set, Promises, JSX, and Server Functions (Server Actions). Not allowed: class instances with methods, regular functions, symbols.
Pass the smallest object you can. Everything you pass to a Client Component is serialized into the HTML/RSC payload and visible to the user. Never pass a full database row that contains password hashes, tokens or internal flags.
Context providers
Render providers as deep as possible and keep them thin:
// app/providers.tsx
'use client'
import { ThemeProvider } from './theme-context'
export function Providers({ children }: { children: React.ReactNode }) {
return <ThemeProvider>{children}</ThemeProvider>
}
// app/layout.tsx
import { Providers } from './providers'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<Providers>{children}</Providers>
</body>
</html>
)
}
Guard server code
// lib/dal.ts
import 'server-only'
Install the tiny server-only package. If any Client Component imports this module, the build fails instead of leaking server code. The mirror package client-only exists for browser-only modules.
5. Data fetching
Fetch where the data is used
In the App Router you fetch inside the Server Component that needs the data. There is no getServerSideProps. Avoid “fetch everything in the page and prop-drill”.
async function Author({ id }: { id: string }) {
const author = await getAuthor(id)
return <span>{author.name}</span>
}
Deduplicate with React.cache
If several components need the same record during one request, wrap the loader in cache so it runs once per request:
// lib/data.ts
import 'server-only'
import { cache } from 'react'
export const getUser = cache(async (id: string) => {
return db.user.findUnique({ where: { id } })
})
React.cache is request-scoped memoization. It is not a persistent cache; for that, use "use cache" (next section).
Avoid waterfalls
Sequential awaits that do not depend on each other add up:
// Slow: 3 round trips one after another
const user = await getUser(id)
const posts = await getPosts(id)
const stats = await getStats(id)
Start them together:
const [user, posts, stats] = await Promise.all([getUser(id), getPosts(id), getStats(id)])
Even better, split the UI so each part streams on its own:
export default function Page(props: PageProps<'/u/[id]'>) {
return (
<>
<Suspense fallback={<HeaderSkeleton />}>
<UserHeader params={props.params} />
</Suspense>
<Suspense fallback={<PostsSkeleton />}>
<UserPosts params={props.params} />
</Suspense>
</>
)
}
Stream a promise into a Client Component
Start the fetch on the server, do not await it, and let the client unwrap it with use():
// app/page.tsx
import { Suspense } from 'react'
import { Reviews } from './_components/reviews'
export default function Page() {
const reviewsPromise = getReviews() // not awaited
return (
<Suspense fallback={<p>Loading reviews...</p>}>
<Reviews reviewsPromise={reviewsPromise} />
</Suspense>
)
}
// app/_components/reviews.tsx
'use client'
import { use } from 'react'
export function Reviews({ reviewsPromise }: { reviewsPromise: Promise<Review[]> }) {
const reviews = use(reviewsPromise)
return <ul>{reviews.map((r) => <li key={r.id}>{r.text}</li>)}</ul>
}
Client-side fetching
Use client fetching (SWR, TanStack Query, or plain fetch in an effect) only for data that is truly client-driven: infinite scroll, live polling, search-as-you-type, user-specific widgets on otherwise static pages. Do not fetch your own Route Handlers from Server Components; call the underlying function directly instead and skip the extra HTTP hop.
Talking to the database directly
A Server Component can query the database directly. Put those queries in a data access layer (DAL) that also performs authorization, so every page gets the same checks:
// lib/dal.ts
import 'server-only'
import { cache } from 'react'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
export const verifySession = cache(async () => {
const token = (await cookies()).get('session')?.value
const session = token ? await decrypt(token) : null
if (!session?.userId) redirect('/login')
return { userId: session.userId as string }
})
export async function getMyInvoices() {
const { userId } = await verifySession()
return db.invoice.findMany({
where: { ownerId: userId },
select: { id: true, total: true, status: true }, // return only what the UI needs
})
}
6. Caching with Cache Components
Next.js 16 introduced Cache Components: caching is explicit and opt-in with the "use cache" directive, and the framework prerenders a static shell around anything cached. New apps created with create-next-app defaults have it on. For existing apps, enable it in config:
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
The docs recommend setting partialPrefetching explicitly when you enable Cache Components, and say both options will become the default (and be removed) in the next major version.
Cache a data function
// lib/products.ts
import { cacheLife, cacheTag } from 'next/cache'
export async function getProducts() {
'use cache'
cacheLife('hours')
cacheTag('products')
return db.product.findMany()
}
Cache a component
async function FeaturedProducts() {
'use cache'
cacheLife('days')
const products = await getFeatured()
return <ProductGrid products={products} />
}
Rules of thumb
- Pair every
"use cache"with acacheLife. Without one, thedefaultprofile applies. - Arguments and captured variables become the cache key.
getProduct(id)caches one entry perid. - Do not read
cookies(),headers()orsearchParamsinside a"use cache"function. Read them outside and pass the values in as arguments, or use"use cache: private"for per-user results that may be prefetched. - Wrap anything request-specific in
<Suspense>. Uncached fetches and runtime APIs without a Suspense boundary are flagged in development as a blocking route. - Short lifetimes are excluded from prerendering. The
secondsprofile,revalidate: 0, or anexpireunder five minutes turns the result into a dynamic hole. - The default store is in-memory per instance. On serverless that is short-lived.
"use cache: remote"stores results in a shared cache handler, which pays off only at a high hit rate. - Cache entries are scoped to a deployment. A new deploy starts with a fresh cache.
Built-in cacheLife profiles
| Profile | Typical use |
|---|---|
seconds |
Near-real-time data (treated as dynamic) |
minutes |
Feeds, dashboards that tolerate a minute of staleness |
hours |
Product listings, search indexes |
days |
Blog posts, docs pages |
weeks |
Rarely edited content |
max |
Content revalidated only on demand (CMS + webhook) |
You can pass a custom object instead: cacheLife({ stale: 300, revalidate: 900, expire: 86400 }) (seconds). See the cacheLife reference for the exact numbers behind each profile.
Per-request values: random IDs and timestamps
Math.random(), Date.now() and crypto.randomUUID() must be deliberate. Either cache them (everyone sees the same value until revalidation) or move them to request time:
import { connection } from 'next/server'
async function RequestId() {
await connection() // defer to request time
return <p>{crypto.randomUUID()}</p>
}
// Render <RequestId /> inside <Suspense>.
Maximize the static shell
Await runtime data as deep in the tree as possible. A layout that awaits params at the top blocks the whole layout; a layout that passes the params promise down and awaits it inside a Suspense boundary lets everything else prerender.
If you are not on Cache Components yet
The previous model still works when cacheComponents is off: fetch(url, { next: { revalidate: 3600, tags: ['x'] } }), route segment config such as export const revalidate = 3600 and export const dynamic = 'force-dynamic'. Plan a migration; the official migration guide walks through it step by step.
7. Revalidation
| API | Where | Behavior | Use it for |
|---|---|---|---|
cacheLife(...) |
Inside "use cache" |
Time-based | Data that can be a little stale |
updateTag(tag) |
Server Actions only | Expires immediately; the user sees their change | Read-your-own-writes after a form submit |
revalidateTag(tag, 'max') |
Server Actions and Route Handlers | Stale-while-revalidate | CMS webhooks, background refresh |
revalidatePath(path) |
Server Actions and Route Handlers | Invalidates everything for a path | When you do not know the tags |
refresh() |
Server Actions only | Reruns dynamic work for the current route without invalidating server-side cached data | Uncached data shown on the current page |
// app/posts/actions.ts
'use server'
import { updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) {
const { userId } = await verifySession()
const post = await db.post.create({
data: { title: String(formData.get('title')), authorId: userId },
})
updateTag('posts')
redirect(`/posts/${post.id}`)
}
// app/api/revalidate/route.ts (called by your CMS webhook)
import { revalidateTag } from 'next/cache'
export async function POST(request: Request) {
if (request.headers.get('x-webhook-secret') !== process.env.WEBHOOK_SECRET) {
return new Response('Unauthorized', { status: 401 })
}
const { tag } = await request.json()
revalidateTag(tag, 'max')
return Response.json({ revalidated: true })
}
Best practices:
- Prefer tags over paths. Tags hit exactly the data that changed; paths over-invalidate.
- Name tags after entities:
posts,post:123,user:42:invoices. Tag both the list and the item so you can invalidate either. - Verify webhook signatures (or at least a shared secret compared in constant time) before revalidating.
8. Server Actions and mutations
A Server Action is an async function marked with "use server" that the client can call. React sends a POST request to the current route, Next.js runs the function on the server, and the result streams back together with any updated UI.
Define actions in their own file
// app/todos/actions.ts
'use server'
import { z } from 'zod'
import { updateTag } from 'next/cache'
import { verifySession } from '@/lib/dal'
const TodoSchema = z.object({
title: z.string().trim().min(1, 'Title is required').max(200),
})
export type TodoState = { error?: string; ok?: boolean }
export async function addTodo(_prev: TodoState, formData: FormData): Promise<TodoState> {
const { userId } = await verifySession() // 1. authenticate
const parsed = TodoSchema.safeParse({ // 2. validate
title: formData.get('title'),
})
if (!parsed.success) {
return { error: parsed.error.issues[0]?.message ?? 'Invalid input' }
}
await db.todo.create({ // 3. mutate (scoped to the user)
data: { title: parsed.data.title, ownerId: userId },
})
updateTag(`todos:${userId}`) // 4. update caches
return { ok: true }
}
Use the form with progressive enhancement
// app/todos/_components/new-todo.tsx
'use client'
import { useActionState } from 'react'
import { addTodo, type TodoState } from '../actions'
export function NewTodo() {
const [state, formAction, pending] = useActionState<TodoState, FormData>(addTodo, {})
return (
<form action={formAction}>
<input name="title" required maxLength={200} aria-describedby="todo-error" />
<button disabled={pending}>{pending ? 'Adding...' : 'Add'}</button>
{state.error && <p id="todo-error" role="alert">{state.error}</p>}
</form>
)
}
The form works before JavaScript loads, because action posts to the server.
Optimistic UI
'use client'
import { useOptimistic } from 'react'
export function TodoList({ todos, toggle }: { todos: Todo[]; toggle: (id: string) => Promise<void> }) {
const [optimistic, setOptimistic] = useOptimistic(
todos,
(current, id: string) => current.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
)
return (
<ul>
{optimistic.map((t) => (
<li key={t.id}>
<form
action={async () => {
setOptimistic(t.id)
await toggle(t.id)
}}
>
<button>{t.done ? 'Undo' : 'Done'}</button> {t.title}
</form>
</li>
))}
</ul>
)
}
Server Action rules
- Treat every action like a public POST endpoint. Authenticate and authorize inside the action. Hiding the button in the UI is not access control.
- Validate every input with a schema (Zod, Valibot, ArkType).
FormDatavalues are alwaysstring | File | null. - Scope writes to the current user (
where: { id, ownerId: userId }), never trust an ID from the form alone. - Return serializable, minimal results. Return error messages, not stack traces.
- Do not put
redirect()insidetry/catch, or rethrow it; it works by throwing. - Keep actions for mutations. For reads, fetch in Server Components. Actions run one at a time per client and are not meant for data fetching.
- Bind extra arguments with
.bind, not hidden inputs, when the value should not be editable:deletePost.bind(null, post.id)(still re-check ownership on the server). - Rate-limit expensive or abusable actions (signup, password reset, AI calls) by user or IP.
Use after() for work that should not block the response
import { after } from 'next/server'
export async function submitFeedback(formData: FormData) {
'use server'
await saveFeedback(formData)
after(async () => {
await sendSlackNotification('New feedback') // runs after the response is sent
})
}
9. Route Handlers
Use Route Handlers (app/**/route.ts) for webhooks, public JSON APIs, file downloads, OAuth callbacks and anything called by third parties. For your own UI, prefer Server Components (reads) and Server Actions (writes).
// app/api/products/[id]/route.ts
import { NextResponse } from 'next/server'
export async function GET(_req: Request, ctx: RouteContext<'/api/products/[id]'>) {
const { id } = await ctx.params
const product = await getPublicProduct(id)
if (!product) return NextResponse.json({ error: 'Not found' }, { status: 404 })
return NextResponse.json(product)
}
Tips:
- Use the Web
Request/ResponseAPIs.request.json(),request.formData(),Response.json(). - Verify webhooks with the provider’s signature check on the raw body (
await request.text()) before parsing. - Set CORS headers per route when a handler is meant for other origins; do not open everything.
- With Cache Components enabled,
GEThandlers follow the same prerendering rules as pages: use"use cache"for cached responses and runtime APIs for request-time ones. page.tsxandroute.tscannot live in the same segment.
10. Proxy (formerly middleware)
Since Next.js 16 the middleware file convention is deprecated and renamed to proxy. The file is proxy.ts at the project root (or in src/), the exported function is proxy, and it runs on the Node.js runtime by default. A codemod renames existing files:
npx @next/codemod@canary middleware-to-proxy .
// proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const hasSession = request.cookies.has('session')
if (!hasSession && request.nextUrl.pathname.startsWith('/dashboard')) {
const url = new URL('/login', request.url)
url.searchParams.set('next', request.nextUrl.pathname)
return NextResponse.redirect(url)
}
return NextResponse.next()
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)'],
}
Best practices:
- Use Proxy for cheap, optimistic checks only: redirects, rewrites, locale detection, A/B bucketing, adding headers. Do not query the database on every request here.
- Never rely on Proxy alone for authorization. Server Actions are POST requests to the page route, so a matcher change can silently drop coverage. Check auth in the DAL, in each action and in each handler.
- Always set a
matcher. Without one, Proxy runs for every request, including static files and images. - Prefer config (
redirects,rewrites,headersinnext.config.ts) for static rules; it is simpler and faster.
11. Loading, errors and not-found
loading.tsx
Adds an instant loading state for a segment by wrapping page.tsx in <Suspense>. Use it for coarse skeletons; use explicit <Suspense> boundaries for finer-grained streaming.
error.tsx
// app/dashboard/error.tsx
'use client'
import { useEffect } from 'react'
export default function DashboardError({ error, retry }: { error: unknown; retry: () => void }) {
useEffect(() => {
reportError(error) // send to your error tracker
}, [error])
return (
<div role="alert">
<h2>Something went wrong loading the dashboard.</h2>
<button onClick={() => retry()}>Try again</button>
</div>
)
}
retry()(stable since 16.3) re-fetches and re-renders the segment.reset()only clears the error state without re-fetching, so preferretry().- In production, errors from Server Components reach the client with a generic message and a
digestyou can match in server logs. Do not depend onerror.messagefor user-facing text. error.tsxdoes not catch errors in thelayout.tsxof the same segment. Useglobal-error.tsxfor the root layout; it must render its own<html>and<body>.
Component-level boundaries with catchError
Since 16.3, catchError from next/error creates an error boundary you can place anywhere, with the same retry() behavior and correct handling of redirect() and notFound():
// components/widget-boundary.tsx
'use client'
import { catchError, type ErrorInfo } from 'next/error'
function Fallback(props: { name: string }, { retry }: ErrorInfo) {
return (
<div role="alert">
{props.name} failed to load. <button onClick={() => retry()}>Retry</button>
</div>
)
}
export default catchError(Fallback)
<WidgetBoundary name="Revenue chart">
<RevenueChart />
</WidgetBoundary>
Expected errors are return values, not exceptions
Validation failures, “email already taken” and similar outcomes should be returned from Server Actions and rendered with useActionState. Reserve thrown errors for unexpected failures.
notFound()
import { notFound } from 'next/navigation'
const post = await getPost(slug)
if (!post) notFound()
Renders the nearest not-found.tsx with a 404 status (or a noindex meta tag when the response has already started streaming).
12. Metadata and SEO
Static and dynamic metadata
// app/layout.tsx
import type { Metadata } from 'next'
export const metadata: Metadata = {
metadataBase: new URL('https://example.com'),
title: { default: 'Acme', template: '%s | Acme' },
description: 'Acme makes project tracking simple.',
openGraph: { type: 'website', siteName: 'Acme' },
}
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next'
export async function generateMetadata(props: PageProps<'/blog/[slug]'>): Promise<Metadata> {
const { slug } = await props.params
const post = await getPost(slug) // deduped with the page's call if wrapped in React.cache
return {
title: post.title,
description: post.excerpt,
alternates: { canonical: `/blog/${slug}` },
openGraph: { title: post.title, images: [post.coverImage] },
}
}
Sitemaps and robots
// app/sitemap.ts
import type { MetadataRoute } from 'next'
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const posts = await getAllPosts()
return [
{ url: 'https://example.com', lastModified: new Date() },
...posts.map((p) => ({ url: `https://example.com/blog/${p.slug}`, lastModified: p.updatedAt })),
]
}
// app/robots.ts
import type { MetadataRoute } from 'next'
export default function robots(): MetadataRoute.Robots {
return {
rules: { userAgent: '*', allow: '/', disallow: ['/dashboard/', '/api/'] },
sitemap: 'https://example.com/sitemap.xml',
}
}
Open Graph images
Add opengraph-image.tsx next to a page and return an ImageResponse from next/og, or drop a static opengraph-image.png into the segment. Generated images are cached like other route output.
SEO checklist
- Set
metadataBaseonce so relative OG URLs resolve. - Give every indexable page a unique
title,descriptionandcanonical. - Add
noindexto search results, dashboards and staging (robots: { index: false }). - Use semantic HTML (
<main>,<nav>, one<h1>per page) and descriptivealttext. - Add JSON-LD structured data with a
<script type="application/ld+json">tag rendered from a Server Component. Escape<in the JSON string so content cannot break out of the script tag. - Keep important content in the server-rendered HTML, not behind client-only fetches.
13. Performance
Images
import Image from 'next/image'
import hero from './hero.jpg' // static import: width/height/blur inferred
<Image src={hero} alt="Team at work" loading="eager" fetchPriority="high" placeholder="blur" sizes="100vw" />
- Always set
sizesfor responsive images; without it the browser may download a much larger file than needed. - For the Largest Contentful Paint (hero) image, use
loading="eager"plusfetchPriority="high", orpreloadwhen the browser must start the download before it sees the<img>. The oldpriorityprop is deprecated since Next.js 16 (see the Image docs). - The default
qualitiesconfig is[75]since Next.js 16; add other values toimages.qualitiesif you pass a differentquality. - Configure
images.remotePatternsnarrowly; do not allow every host.
Fonts
// app/layout.tsx
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'], display: 'swap' })
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className={inter.className}>
<body>{children}</body>
</html>
)
}
next/font self-hosts the font files at build time, so there is no request to Google at runtime and no layout shift from late font swaps.
Third-party scripts
import Script from 'next/script'
<Script src="https://example.com/analytics.js" strategy="lazyOnload" />
Use afterInteractive (default) for things that must run soon, lazyOnload for chat widgets and analytics that can wait.
JavaScript size
- Keep
"use client"boundaries small; every import under a client boundary ships to the browser. -
Lazy-load heavy client-only widgets:
'use client' import dynamic from 'next/dynamic' const Editor = dynamic(() => import('./editor'), { ssr: false, loading: () => <p>Loading editor...</p> })(
ssr: falseis only allowed inside Client Components.) - Import only what you use from large libraries (
import debounce from 'lodash/debounce') or rely on packages with good tree shaking. - Inspect bundles with
@next/bundle-analyzerbefore and after adding dependencies.
Rendering
- Prefer a large static shell with small dynamic holes (see Caching).
- Put
<Suspense>boundaries around slow, independent parts so they stream in parallel. - Use
<Link>prefetching (default) and avoidprefetch={false}unless a link is rarely used and expensive. - Measure with real-user Core Web Vitals (
useReportWebVitalsfromnext/web-vitals, or your hosting provider’s analytics), not just Lighthouse on a fast laptop.
Build tooling
Turbopack is the default bundler for next dev and next build in Next.js 16. If you depend on custom webpack configuration, next build --webpack keeps the old bundler while you migrate.
14. Security
Threat model in one table
| Surface | Risk | Defense |
|---|---|---|
| Server Actions | Anyone can POST to them | Auth + authz + validation inside each action |
| Route Handlers | Public endpoints | Same as above; verify webhook signatures |
| Props to Client Components | Data leaks into HTML | Pass DTOs with only needed fields |
| Environment variables | Secrets shipped to the browser | Only NEXT_PUBLIC_* reaches the client; keep secrets unprefixed |
| Proxy-only auth | Bypassed by matcher gaps | Check auth in the data layer too |
dangerouslySetInnerHTML |
XSS | Sanitize HTML or render Markdown on the server with a safe renderer |
| Redirects with user input | Open redirect | Allow-list internal paths before redirect(next) |
Use a Data Access Layer
Centralize data reads in server-only modules that check the session and return data transfer objects, not raw rows. Components then cannot accidentally fetch or leak something they should not. The official data security guide describes this pattern in depth.
Sessions and cookies
- Store sessions in
HttpOnly,Secure,SameSite=Lax(orStrict) cookies. - Set cookies from Server Actions or Route Handlers via
(await cookies()).set(...). Server Components can read cookies but cannot set them. - Use a maintained auth library rather than rolling your own crypto.
Content Security Policy and headers
// next.config.ts
import type { NextConfig } from 'next'
const securityHeaders = [
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=()' },
{ key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' },
]
const nextConfig: NextConfig = {
async headers() {
return [{ source: '/(.*)', headers: securityHeaders }]
},
}
export default nextConfig
For a strict CSP with nonces, generate the nonce in proxy.ts and read it in your layout; nonce-based CSP forces dynamic rendering, so weigh it against caching. The official CSP guide has the full recipe.
Safe redirects after login
function safeNext(next: string | null) {
// only allow same-site relative paths like "/dashboard"
return next && next.startsWith('/') && !next.startsWith('//') ? next : '/'
}
Keep dependencies patched
Next.js and React publish security advisories. Follow the security posts on the Next.js blog, run npm audit (or your package manager’s equivalent) in CI, and upgrade patch versions promptly.
15. Environment variables and configuration
.env,.env.local,.env.development,.env.productionare loaded automatically. Commit.env.example, never.env.local.- Only variables prefixed with
NEXT_PUBLIC_are inlined into client code, at build time. Changing them requires a rebuild. - Server-only variables are read at runtime with
process.env.NAMEin server code. -
Validate env vars once at startup so a missing secret fails fast:
// lib/env.ts import 'server-only' import { z } from 'zod' export const env = z .object({ DATABASE_URL: z.string().url(), SESSION_SECRET: z.string().min(32), }) .parse(process.env) - Use
next.config.ts(TypeScript config is supported) and keep it small. Prefer framework defaults over flags you do not understand.
16. Testing
| Layer | Tool | What to test |
|---|---|---|
| Pure functions, validation schemas, DAL helpers | Vitest or Jest | Inputs and outputs, authorization branches |
| Client Components | React Testing Library | Interaction and rendering |
| Async Server Components, full flows | Playwright | Real pages against next build && next start |
| Proxy | next/experimental/testing/server helpers |
Matchers and redirects |
Tips:
- Test Server Actions as plain async functions: build a
FormData, call the action, assert the database and the returned state. Mock the session helper. - Run end-to-end tests against a production build; dev mode behaves differently (no prerendering, extra checks).
- Add a test for each authorization rule: “user B cannot read or edit user A’s invoice”.
17. Deployment and self-hosting
- Any Node.js host:
next build && next start. Next.js 16 requires a current Node.js LTS (check the installation docs for the minimum). - Docker: set
output: 'standalone'innext.config.tsso the build emits a minimal server in.next/standalone; copypublic/and.next/static/next to it in your image. - Static export:
output: 'export'builds plain HTML/CSS/JS for any static host, but you lose Server Actions, Proxy, ISR and request-time rendering. - Multiple instances: the default cache is per instance and in memory. Configure a shared cache handler if instances must share cached data, and set a stable build ID across instances of the same deploy.
- Observability: add
instrumentation.tsto register OpenTelemetry or your error tracker, and useonRequestErrorto report server errors.
Minimal standalone Dockerfile:
FROM node:24-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM node:24-alpine AS build
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:24-alpine AS run
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup -S app && adduser -S app -G app
COPY --from=build /app/public ./public
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
USER app
EXPOSE 3000
CMD ["node", "server.js"]
18. Common mistakes and fixes
| Symptom | Cause | Fix |
|---|---|---|
| “Functions cannot be passed directly to Client Components” | Passing a normal function as a prop across the boundary | Make it a Server Action ("use server") or move the logic into the Client Component |
useState error in a page |
Hooks used in a Server Component | Extract the interactive part into a "use client" component |
| Whole route is dynamic or flagged as blocking | cookies()/headers()/uncached fetch outside <Suspense> |
Move the access into a child wrapped in <Suspense> or cache it |
| Data does not update after a form submit | Cache not invalidated | updateTag / revalidatePath in the action |
redirect() “does nothing” |
Called inside try/catch that swallows it |
Call it after the try/catch, or rethrow |
| Secret appears in the browser bundle | Imported a server module from a Client Component, or used NEXT_PUBLIC_ |
Add import 'server-only'; rename the variable |
| Hydration mismatch | Rendering Date.now(), Math.random() or window on the server |
Compute on the client in an effect, or render it on the server only |
| Slow page with many awaits | Sequential waterfalls | Promise.all or separate Suspense boundaries |
| Proxy blocks CSS and images | No matcher |
Add a negative matcher for _next/static, _next/image and public files |
| Huge client bundle | "use client" at the top of a layout |
Move the directive to leaf components |
params.slug is undefined |
params is a Promise |
const { slug } = await props.params |
Fetching /api/... from a Server Component |
Unneeded HTTP hop (and fails at build time) | Call the function directly |
19. Production checklist
Architecture
- Server Components by default;
"use client"only on interactive leaves - Data access layer with
import 'server-only'and DTOs - No fetching of your own Route Handlers from server code
Data and caching
- Cache Components enabled (or a documented plan to migrate)
- Every
"use cache"has acacheLifeand, where needed, acacheTag - Runtime data wrapped in
<Suspense>with meaningful fallbacks - Mutations call
updateTag/revalidateTag/revalidatePath
Security
- Auth and authorization inside every Server Action and Route Handler
- Input validation with a schema everywhere data enters
- Webhooks verified by signature
- Security headers (and CSP if feasible) configured
- No secrets in
NEXT_PUBLIC_*; env vars validated at startup - Rate limiting on auth and expensive endpoints
UX and resilience
loading.tsxor Suspense for slow routeserror.tsxper major section,global-error.tsxat the rootnot-found.tsxandnotFound()for missing records- Forms work without JavaScript and show pending and error states
Performance and SEO
next/imagewithsizes; LCP image eager-loaded with high fetch prioritynext/fontfor fonts- Bundle analyzed; heavy widgets lazy-loaded
metadataBase, titles, descriptions, canonicals,sitemap.ts,robots.ts- Core Web Vitals monitored in production
Operations
instrumentation.tsreporting errors and traces- E2E tests run against a production build
- Dependency and security updates on a schedule
20. Further reading
Official documentation:
- Next.js documentation
- Caching (Cache Components)
- Revalidating
use cachedirectiveproxy.jsfile conventionerror.jsfile conventioncatchError- Data security guide
- Next.js 16 release post
- Learn Next.js course
React APIs used in this guide:
Security background:
21. Rendering and data strategies compared
| Strategy | How you get it in Next.js 16 (Cache Components on) | Freshness | Speed | Use for |
|---|---|---|---|---|
| Static (prerendered) | Component uses no runtime data, or only "use cache" data |
Until next deploy or revalidation | Fastest (CDN) | Marketing pages, docs |
| Cached with time revalidation | "use cache" + cacheLife('hours') |
Bounded staleness | Very fast | Catalogs, blog indexes |
| Cached with on-demand revalidation | "use cache" + cacheTag + revalidateTag/updateTag |
Fresh after each change | Very fast | CMS content, product pages |
| Streaming dynamic | Runtime API or uncached fetch inside <Suspense> |
Every request | Shell instant, data streams | Dashboards, personalized widgets |
| Per-user cached | "use cache: private" |
Per user, per cacheLife |
Fast navigations | Prefetchable user-specific content |
| Client-side fetching | SWR / TanStack Query in a Client Component | As often as you poll | Depends on client | Live data, infinite scroll |
| Static export | output: 'export' |
Build time only | Fastest, any host | Sites without a server |
22. Choosing libraries
Next.js does not ship auth, a database layer or validation. Popular, actively maintained choices (links checked December 2026):
| Need | Options | Pick it when |
|---|---|---|
| Authentication | Auth.js, Better Auth, Clerk, Supabase Auth | Auth.js / Better Auth: self-hosted, open source, your own DB. Clerk: hosted with prebuilt UI. Supabase Auth: you already use Supabase. |
| Database access | Prisma, Drizzle ORM, Kysely | Prisma: schema-first with migrations and a rich client. Drizzle: SQL-like TypeScript API, light. Kysely: type-safe query builder without an ORM. |
| Validation | Zod, Valibot | Zod: most examples and integrations. Valibot: smaller bundles for client-side validation. |
| Client data fetching | TanStack Query, SWR | TanStack Query: complex caching, mutations, devtools. SWR: minimal API for simple polling and revalidation. |
| Testing | Vitest, Playwright | Vitest for units, Playwright for end-to-end against a production build. |
| Themes | next-themes | Dark mode toggle without a flash of the wrong theme. |
| Self-hosting adapters | OpenNext | Running Next.js on providers other than Vercel or a plain Node server. |
Best picks for a typical new SaaS app: Server Components + Server Actions for most reads and writes, Drizzle or Prisma behind a server-only data access layer, Zod for validation, Better Auth or Auth.js for sessions (or Clerk if you want hosted UI), Playwright for the critical flows. Add TanStack Query only for truly client-driven data.
23. FAQ
App Router or Pages Router for a new project? The App Router. It is where new features (Server Components, Server Actions, Cache Components, streaming) land. The Pages Router is still supported for existing apps, and both can live in one project during a migration.
Is middleware deprecated?
The middleware.ts file convention is deprecated and renamed to proxy.ts since Next.js 16. Run npx @next/codemod@canary middleware-to-proxy . to migrate. The behavior is the same, and the docs recommend using it only when config-based redirects, rewrites or headers cannot do the job.
Server Actions or Route Handlers? Server Actions for mutations triggered by your own UI (forms, buttons). Route Handlers for anything called by other clients: webhooks, mobile apps, public APIs, file downloads, OAuth callbacks.
Why is my whole page dynamic (or why does dev warn about a blocking route)?
Something reads cookies(), headers(), searchParams, an uncached fetch, or the current time outside a <Suspense> boundary. Move that read into a child component wrapped in <Suspense>, cache it with "use cache", or pass the value down as a promise.
"use cache" vs unstable_cache vs fetch caching?
"use cache" is the Cache Components way and works for any async function or component, not only fetch. unstable_cache and fetch(..., { next: { revalidate } }) belong to the previous caching model; prefer "use cache" in new code.
How do I fetch data in a Client Component?
Best: fetch in a Server Component and pass the data (or an unawaited promise unwrapped with use()) as props. For client-driven data, use SWR or TanStack Query against a Route Handler.
How do I protect pages? Check the session in a server-only data access layer that every page and action uses, and redirect when missing. Proxy can add a fast optimistic redirect, but it must not be your only check. The official authentication guide walks through the full pattern.
Can I deploy without Vercel?
Yes. next start on any Node.js server, the standalone output in Docker, static export for static hosts, or adapters such as OpenNext for other platforms. See the self-hosting guide for caching and ISR setup.
How do I upgrade from Next.js 15?
Follow the version 16 upgrade guide and run the official codemods. Expect to handle async params/searchParams, the middleware to proxy rename, the Turbopack default and image defaults.
Why does my form lose its state after submit?
Return the state from the action and read it with useActionState. To keep input values, set them as defaultValue from the returned state.
24. Where to go next
- Do the official Learn Next.js course if you have not built an App Router app end to end.
- Read the production checklist before launch.
- Read the Server Actions guide and Forms guide for advanced mutation patterns.
- Learn the instant navigation guide to get the most from Cache Components.
- Bookmark the Next.js blog for release notes and security announcements.
- For UI, try the companion repos Ralpberry-Labs/ui-blocks (React + Tailwind blocks) and Ralpberry-Labs/tailwind-components.
Contributing
PRs are welcome. Keep entries accurate and current: link to the official docs for any API you describe, mention the Next.js version where behavior changed, and test code snippets in a real app before submitting. Opinions are fine if they come with a reason.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.