Reference - Next.js
Language: Next.js 16.4 (16.4.3 on npm) — App Router in full, Pages Router mapped. Ships React 19.3 in the App Router
Checked: 2026-10-30
A React framework where the folder tree is the router and every component renders on the server unless marked otherwise. The thing to learn isn’t the routing — it’s which parts of a route are prerendered, which are cached, and which run per request, because Next.js has changed that answer three times since 2023 and your codebase may hold more than one of them.
§0 The one idea
The file system is the router, the server is the default runtime, and the build decides — per route, and now per component — what is static, what is cached and what runs on every request.
vs a client-side React SPA (single-page app): there, the browser downloads one bundle, React renders everything, and data arrives through effects after mount. Routing is a library you configure; the server only serves files. In Next.js the server renders first, components that never need interactivity never ship as JavaScript, and a URL is a folder.
REACT SPA (Vite + React Router declarative) NEXT.JS APP ROUTER
routes defined in code routes = folders under app/
every component ships to the browser components are SERVER by default
'use client' marks the exceptions
data: useEffect → fetch → setState data: await it in the component,
after mount, waterfall by tree depth on the server, before HTML is sent
server: static file host server: renders HTML + RSC payload,
runs actions, route handlers, proxy
caching: your problem (TanStack Query…) caching: the framework's — prerender
at build, 'use cache', revalidate
The consequence worth holding: almost every Next.js bug report reduces to “this ran somewhere I didn’t expect” (server vs client) or “this was cached when I didn’t expect” (build vs request). The rungs below are ordered so each of those two questions gets answered before the next feature leans on it.
vs React Router framework mode — the main alternative — Reference - React Router. Both are server-first React. React Router puts data in route-level loader/action functions and leans on HTTP caching; Next.js puts data inside components (Server Components) and owns a caching layer of its own. React Router is easier to predict; Next.js gives finer-grained static/dynamic mixing within one page.
What Next.js adds, and what’s just React
A framework reference’s job is subtraction. Much of what feels like “Next.js magic” is React.
| Feels like Next.js | Actually |
|---|---|
Server Components, 'use client', 'use server' | React — Server Components, Reference - React. Next.js supplies the bundler wiring that makes them work |
<Suspense> streaming, use(), useActionState, useOptimistic | React |
<form action={fn}> | React 19 form actions. Next.js adds the server endpoint behind 'use server' |
async components | React (server only) |
fetch, Request, Response, FormData, Headers | Web platform. Next.js historically patched fetch to add caching — see rung 5 |
File-system routing, layouts, loading/error/not-found files | Next.js — a convention that generates Suspense and error boundaries for you |
'use cache', cacheLife, cacheTag, revalidateTag, revalidatePath | Next.js |
| Prerendering at build, ISR (Incremental Static Regeneration) | Next.js — Static Generation and Revalidation |
proxy.ts (was middleware.ts), route handlers, metadata API | Next.js |
next/image, next/font, next/link, next/navigation | Next.js |
| Global CDN purge, Skew Protection, image optimisation as a service | Vercel, reading Next’s build output — Vercel |
Two routers, one framework
my-app/
├── app/ ← APP ROUTER (2023+). Server Components, layouts, actions, 'use cache'
├── pages/ ← PAGES ROUTER (2016+). getServerSideProps, _app, API routes
└── proxy.ts ← shared by both. one file per project
Both are fully supported in 16.4 and can live in one app. The App Router is where all new work goes; the Pages Router is maintained, not developed. Everything from rung 1 to the kitchen sink is App Router. The Pages Router appears in its own section as a mapping table.
The caching timeline — read this before any code
Next.js changed its caching defaults in 15 and introduced a new model in 16. A codebase upgraded in place carries the semantics of whichever version it was written against, so “what does this do” depends on the version and the config flag.
NEXT 14 NEXT 15 / 16 (no flag) NEXT 16 + cacheComponents: true
"previous model" "Cache Components"
fetch() default CACHED (force-cache) not cached not cached; 'use cache' to cache
↑ BUT see below
GET route handler cached not cached prerendered like a page if it
touches nothing request-time
route static or whole route: static whole route: static PER COMPONENT. static shell +
dynamic? unless a dynamic unless a dynamic API streamed dynamic holes (PPR)
API is used (cookies/headers…) used
caching config fetch options, same 'use cache' + cacheLife +
unstable_cache, cacheTag. segment configs
export const revalidate / dynamic /
revalidate/dynamic fetchCache / dynamicParams
are REMOVED or error
client router cache dynamic pages reused staleTime 0 for pages 'use cache' output cached in
for 30s the browser for its stale time
navigation state unmount on leave unmount on leave routes kept in <Activity hidden>
— useState survives back/forward
- Cache Components is the recommended model from 16.4:
create-next-appenables it by default, and the release post says it becomes the default in Next.js 17. Existing apps are mostly still on the previous model. Checknext.configforcacheComponentsbefore reasoning about any page - PPR (Partial Prerendering — a static HTML shell served instantly, with dynamic parts streamed into Suspense holes in the same response) was
experimental.pprin 14–15. Next 16 removed that flag; PPR is now simply how Cache Components renders dynamicIOwas the 15-era experimental name for the same thing, renamed tocacheComponentsin 16- The trap in the middle column: “fetch is not cached” does not mean “the page is dynamic”. A route with no request-time API is still prerendered at build, and any
fetchreached before a request-time API runs once, at build, and is baked into the HTML. Uncached fetch, static page, stale data — the most common Next 15 surprise
1. The smallest working form
Two files. This is a complete, deployable Next.js app.
// app/layout.tsx — the root layout. Required; owns <html> and <body>
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en-GB">
<body>{children}</body>
</html>
);
}// app/page.tsx — the route "/"
export default function Home() {
return <h1>Hello</h1>;
}That’s the whole thing. No router config, no index.html, no ReactDOM.createRoot. Both are Server Components: neither ships its code to the browser. With no data and no interactivity, the build prerenders / to static HTML.
package.json scripts are next dev, next build, next start. Turbopack is the default bundler from 16; --webpack opts out.
2. Routes, layouts and special files
Folders are URL segments. A segment becomes public when it contains page.tsx (UI) or route.ts (an API endpoint) — never both in one segment.
app/
├── layout.tsx wraps everything
├── page.tsx /
├── not-found.tsx any unmatched URL, or notFound() called
├── global-error.tsx errors in the root layout itself
├── shop/
│ ├── layout.tsx wraps /shop and below. persists across child navigation
│ ├── loading.tsx instant fallback while shop/** renders → a <Suspense>
│ ├── error.tsx catches render errors in shop/** → an error boundary
│ ├── page.tsx /shop
│ └── [slug]/page.tsx /shop/red-shoes params.slug = "red-shoes"
├── docs/[...path]/page.tsx /docs/a/b params.path = ["a","b"] catch-all
├── help/[[...path]]/page.tsx /help AND /help/a/b optional catch-all
├── (marketing)/ ROUTE GROUP — no URL segment. shares a layout
│ ├── layout.tsx
│ └── about/page.tsx /about not /marketing/about
└── _components/ PRIVATE FOLDER — "_" opts it out of routing
The special files compile to React primitives. For a segment, Next.js nests them like this:
<Layout>
<ErrorBoundary fallback={<Error />}> ← error.tsx (must be 'use client')
<Suspense fallback={<Loading />}> ← loading.tsx
<ErrorBoundary fallback={<NotFound />}> ← not-found.tsx
<Page />
So the error boundary sits inside the layout: an error in /shop/[slug] leaves the shop navigation working. An error in layout.tsx is caught by the parent segment’s error.tsx.
A dynamic segment. params is a Promise from Next 15 onwards — awaited, not destructured:
// app/shop/[slug]/page.tsx
export default async function Product({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params; // sync access was removed in 16
return <h1>{slug}</h1>;
}Equivalent form: PageProps<'/shop/[slug]'> is a generated global type that types the same props from the route string — async function Product(props: PageProps<'/shop/[slug]'>). Same thing, less typing.
Layouts persist; templates don’t. Navigating /shop/a → /shop/b keeps shop/layout.tsx mounted (state and all) and re-renders only the page. template.tsx is a layout that remounts on every navigation — rare. Route groups with separate root layouts cause a full page reload when navigating between them.
Less common conventions, for recognition: default.tsx (parallel route fallback — required for every parallel slot from 16), @slot folders (parallel routes), (.)folder (intercepting routes — the “modal over the list” pattern). See Routing for the general model.
3. Server by default, and the 'use client' boundary
The React-level model belongs to Server Components and Reference - React. What matters here is how Next.js applies it.
Every file under app/ is a Server Component unless it, or a file importing it, sits below a 'use client' directive. A Server Component can be async, read the database, use secrets. It can’t use state, effects, event handlers or browser APIs.
// app/shop/[slug]/add-button.tsx
'use client'; // ← this file and everything IT imports ship to the browser
import { useState } from 'react';
export function AddButton({ sku }: { sku: string }) {
const [added, setAdded] = useState(false);
return <button onClick={() => setAdded(true)}>{added ? 'Added' : `Add ${sku}`}</button>;
}// app/shop/[slug]/page.tsx — still a Server Component
import { AddButton } from './add-button';
export default async function Product({ params }) {
const { slug } = await params;
const product = await db.product.find(slug); // server-only. never in the bundle
return (
<>
<h1>{product.name}</h1>
<AddButton sku={product.sku} /> {/* a hole the client fills */}
</>
);
}'use client' marks an entry point, not a component. It goes at the top of the file where the client subtree starts; every module that file imports joins the client bundle without needing its own directive. Put it on a leaf (the button), not a layout — on a layout it drags the whole subtree into the bundle.
What can cross the boundary (server → client props):
| Crosses | Doesn’t |
|---|---|
Strings, numbers, booleans, null, undefined, plain objects, arrays | Functions — onClick={...} from a Server Component throws |
Date, Map, Set, BigInt, typed arrays | Class instances (a Prisma model with methods, a Decimal) |
Promises — pass one, unwrap it with React’s use() in the client | Symbols not registered globally |
Rendered JSX, including as children | |
Server Actions ('use server' functions) — cross as a reference |
The children trick: a Client Component can render a Server Component it receives as children without importing it. That’s how a client-side provider or modal wraps server-rendered content:
// app/layout.tsx (server)
<ThemeProvider>{children}</ThemeProvider> // ThemeProvider is 'use client'; children stay serverFence server code off. import 'server-only' at the top of a module makes the build fail if a Client Component imports it — the guard for DB clients and anything reading secrets. client-only is the mirror.
4. Fetching data
Await it in the component. No getServerSideProps, no loader, no effect:
// app/orders/page.tsx
export default async function Orders() {
const orders = await db.order.findMany(); // or await fetch(...)
return <OrderList orders={orders} />;
}Waterfalls are now your job. Sequential awaits run sequentially. Start independent work together:
const [user, orders] = await Promise.all([getUser(), getOrders()]);Stream the slow part. Wrap it in <Suspense> and the rest of the page is sent first; the slow component streams into the same response when ready — Streaming Responses:
import { Suspense } from 'react';
export default function Page() {
return (
<>
<ProductDetails /> {/* fast */}
<Suspense fallback={<p>Loading reviews…</p>}>
<Reviews /> {/* slow: streams in */}
</Suspense>
</>
);
}loading.tsx is the same thing applied to the whole page.
Deduplication. Two components calling getUser() in one render hit the database twice unless wrapped in React’s cache() (per-request memoisation — a React feature, not a Next one). GET fetch calls with identical URL and options are memoised within a render automatically.
Client-side fetching still exists for data driven by client state (infinite scroll, polling): SWR or TanStack Query in a Client Component, optionally seeded from a server-fetched value. The general trade-offs are in Data Fetching Patterns.
5. Caching and rendering
Where people get lost. State which model you’re in first — see the timeline above.
5a. Cache Components (cacheComponents: true) — the current model
Nothing is cached unless you say so. Anything that doesn’t touch request data or uncached I/O is prerendered into a static shell; everything else runs per request inside a Suspense boundary.
// next.config.ts
const nextConfig = {
cacheComponents: true,
partialPrefetching: true, // part of the model since 16.3. unset logs a warning
};
export default nextConfig;Three kinds of content on one page:
import { Suspense } from 'react';
import { cookies } from 'next/headers';
import { cacheLife, cacheTag } from 'next/cache';
export default function Page() {
return (
<>
<h1>Shop</h1> {/* 1. STATIC — prerendered at build */}
<Bestsellers /> {/* 2. CACHED — in the static shell, revalidates */}
<Suspense fallback={<p>…</p>}>
<Basket /> {/* 3. DYNAMIC — streams per request */}
</Suspense>
</>
);
}
async function Bestsellers() {
'use cache'; // cache this component's output
cacheLife('hours'); // its lifetime (profile — see below)
cacheTag('products'); // a label to invalidate it by
const items = await db.product.bestsellers();
return <List items={items} />;
}
async function Basket() {
const id = (await cookies()).get('basket')?.value; // request-time API → must be under Suspense
return <MiniBasket id={id} />;
}WHAT THE BUILD PRODUCES WHAT A REQUEST GETS
HTML shell: <h1>Shop</h1> ← shell sent immediately (CDN-cacheable)
<Bestsellers> output ← from cache; refreshed after 1 hour
<p>…</p> (fallback) ← hole
← Basket rendered for THIS user,
streamed into the hole, same response
'use cache' rules:
- Goes at the top of an
asyncfunction, a component, or a whole file (caches every export) - Arguments and closed-over values become the cache key automatically. Pass
userIdin and you get one entry per user - Can’t read
cookies()/headers()/searchParamsinside — read them outside and pass the value in, or use'use cache: private', which allows it and caches per-user in the browser - Default storage is in-memory per server instance — evaporates on serverless.
'use cache: remote'uses a configured remote handler for durable, shared entries - Unmarked uncached I/O or a request-time API outside Suspense fails the build/dev check with a “blocking route” error. The error is the feature: it forces you to decide
cacheLife profiles — stale is how long the browser may use it without asking; revalidate is when the server regenerates it in the background; expire is when it must be regenerated before serving:
| Profile | stale | revalidate | expire |
|---|---|---|---|
default (no cacheLife called) | 5 min | 15 min | never |
seconds | 30 s | 1 s | 1 min |
minutes | 5 min | 1 min | 1 hour |
hours | 5 min | 1 hour | 1 day |
days | 5 min | 1 day | 1 week |
weeks | 5 min | 1 week | 30 days |
max | 5 min | 30 days | 1 year |
Custom profiles and overrides go in next.config under cacheLife.
Math.random(), Date.now(), crypto.randomUUID() outside a cache scope are flagged — call await connection() first (opt into request time, under Suspense) or put them in a 'use cache' scope (one value for everyone until revalidation).
Dynamic routes under Cache Components: generateStaticParams must return at least one param; params it doesn’t list render on request (and with 16.3’s ISR changes, serve an instant shell to the first visitor, then get cached). dynamicParams is not allowed — call notFound() instead.
5b. The previous model (no flag) — what most existing code is written against
// fetch-level
await fetch(url, { cache: 'force-cache' }); // cache indefinitely
await fetch(url, { next: { revalidate: 3600, tags: ['products'] } });
await fetch(url, { cache: 'no-store' }); // never cache
// non-fetch (DB queries) — wrapper function
import { unstable_cache } from 'next/cache';
const getProducts = unstable_cache(() => db.product.all(), ['products'], {
revalidate: 3600, tags: ['products'],
});
// route-level — exported from page.tsx / layout.tsx / route.ts
export const revalidate = 3600; // ISR: regenerate at most hourly
export const dynamic = 'force-dynamic'; // 'auto' | 'force-dynamic' | 'force-static' | 'error'
export const dynamicParams = false; // unknown [slug] → 404How the previous model decides static vs dynamic: whole route at a time. Calling cookies(), headers(), reading searchParams, connection(), or a no-store fetch makes the entire route dynamic. Otherwise the route is prerendered at build, including any fetch reached before a request-time API. The lowest revalidate among a route’s layouts, page and fetches wins for the whole route.
Equivalent forms across the two models:
| Intent | Previous model | Cache Components |
|---|---|---|
| Cache a DB query for an hour | unstable_cache(fn, keys, { revalidate: 3600 }) | 'use cache'; cacheLife('hours') in fn |
| Cache a fetch | fetch(url, { cache: 'force-cache' }) | Wrap the fetching function in 'use cache' |
| Page regenerates hourly | export const revalidate = 3600 | 'use cache' + cacheLife on the page or its data |
| Force per-request | export const dynamic = 'force-dynamic' | Default — just put it under Suspense |
| Force static | export const dynamic = 'force-static' | Don’t touch request data. To make the build fail if someone later adds request-time work: export const ensureStatic = 'shell' | 'prefetch' | 'navigation' — static App Shell only, shell plus link prefetches, or the whole route |
| Opt out of a cache | unstable_noStore() / no-store | Default |
5c. Invalidation — same APIs in both models
All from next/cache. Call them after a mutation, in a Server Action or route handler.
| Where | Behaviour | |
|---|---|---|
revalidateTag(tag, profile) | Actions, route handlers | Marks entries with that tag stale. Stale-while-revalidate: next visitor gets old content, regeneration happens in the background. The second argument became required-in-practice in 16 (single-argument form is deprecated); 'max' is the docs’ recommendation |
updateTag(tag) | Server Actions only (16+) | Expires immediately — the same request reads fresh data. Read-your-own-writes: the user who saved sees their change |
revalidatePath(path) | Actions, route handlers | Invalidates everything cached for that path. For when you don’t know the tags |
refresh() | Server Actions only (16+) | Re-renders uncached data on the page; touches no cache. Server-side twin of router.refresh() |
In plain terms: revalidateTag = “this is out of date, fix it when convenient”; updateTag = “this is out of date and the person looking needs the new version now”.
On Vercel, these purge the platform’s caches globally; self-hosted, they purge the instance they ran on unless you configure a shared cache handler — see Where it bites, and Vercel.
6. Server Actions and forms
A Server Action is an async function marked 'use server' that the client can call. Next.js compiles it to a POST endpoint and gives the client a reference. The React side (form actions, useActionState, useOptimistic) is Reference - React; Forms in Frameworks has the comparison.
Smallest form — inline in a Server Component:
// app/newsletter/page.tsx
export default function Page() {
async function subscribe(formData: FormData) {
'use server'; // ← runs on the server
await db.subscriber.create({ email: String(formData.get('email')) });
}
return (
<form action={subscribe}> {/* works before JS loads */}
<input name="email" type="email" required />
<button>Subscribe</button>
</form>
);
}Equivalent form — a separate file, which is the only way a Client Component can use one:
// app/newsletter/actions.ts
'use server'; // every export is an action
import { updateTag } from 'next/cache';
import { redirect } from 'next/navigation';
export async function subscribe(prev: { error?: string }, formData: FormData) {
const email = String(formData.get('email'));
if (!email.includes('@')) return { error: 'Enter a valid email' };
await db.subscriber.create({ email });
updateTag('subscribers');
redirect('/thanks'); // throws — nothing after it runs
}// app/newsletter/form.tsx
'use client';
import { useActionState } from 'react';
import { subscribe } from './actions';
export function SignupForm() {
const [state, action, pending] = useActionState(subscribe, {});
return (
<form action={action}>
<input name="email" type="email" />
{state.error && <p role="alert">{state.error}</p>}
<button disabled={pending}>{pending ? 'Subscribing…' : 'Subscribe'}</button>
</form>
);
}What Next.js adds over React’s form actions:
- One round trip: the action runs, invalidates caches, and the response carries the re-rendered RSC payload for the current page. No refetch call
- Sequential per client: actions from one browser queue one at a time
- Action IDs are encrypted and unused actions are stripped — but every exported action is a public POST endpoint. Hiding the form isn’t access control; authenticate and authorise inside the action, every time
- Not for reads. Actions are POST-only and serialised; fetch data in Server Components
Do you need an API route to mutate? No — that’s the point of actions. Use a route handler only when something other than your own UI calls it (webhooks, a mobile app, a third party).
7. Route handlers — route.ts
An HTTP endpoint inside app/, written against the Web Request/Response API. Replaces Pages Router API routes.
// app/api/stock/[sku]/route.ts
import { NextResponse } from 'next/server';
export async function GET(request: Request, { params }: { params: Promise<{ sku: string }> }) {
const { sku } = await params;
const qty = await stockFor(sku);
return NextResponse.json({ sku, qty }); // or: Response.json(...) — equivalent
}
export async function POST(request: Request) {
const body = await request.json();
// …
return new Response(null, { status: 204 });
}- Export one function per HTTP method:
GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS NextResponseisResponseplus helpers (.json,.redirect,.rewrite, cookie helpers).NextRequestaddsnextUrlandcookies- Caching: Next 14 cached
GETby default; 15+ doesn’t. Under Cache Components aGETthat touches no request data is prerendered like a page route.tsandpage.tsxcan’t share a segment — that’s why they conventionally live underapp/api/- Metadata routes (
sitemap.ts,robots.ts,opengraph-image.tsx) are specialised route handlers and are static by default
8. Proxy — proxy.ts (formerly middleware.ts)
One function that runs before routing, for every request its matcher covers — including requests that will be served from cache. It can redirect, rewrite to another path, set request/response headers or cookies, or respond directly.
// proxy.ts — project root (or src/), beside app/
import { NextResponse, type NextRequest } from 'next/server';
export function proxy(request: NextRequest) {
if (!request.cookies.has('session')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/account/:path*'], // without this it runs on EVERY request, assets included
};Equivalent forms: export function proxy and export default function proxy both work.
Naming by version:
Next 12–15 middleware.ts, export function middleware Edge runtime only (Node from 15.5, stable)
Next 16+ proxy.ts, export function proxy Node.js runtime. `runtime` config not allowed
middleware.ts still works, DEPRECATED — kept only for Edge-runtime use
Where it sits in the order (from the Next docs):
1 headers (next.config)
2 redirects (next.config)
3 PROXY ← rewrites/redirects here
4 beforeFiles rewrites
5 filesystem routes: public/, _next/static, pages/, app/
6 afterFiles rewrites
7 dynamic routes /blog/[slug]
8 fallback rewrites
- Static config first. Fixed redirects and headers belong in
next.config; proxy is for decisions needing logic - Not for slow work or real authorisation. It’s an optimistic gate — re-check auth where the data is read.
fetchcaching options have no effect inside it - One file per project, shared by
app/andpages/ - On Vercel it becomes Routing Middleware, in front of the CDN — which is why it’s the server-side A/B-test assignment point. That pattern, and the Flags SDK precompute approach, live in Vercel and Client-Side vs Server-Side Testing
9. Metadata
Export an object or a function from a layout.tsx or page.tsx. Server Components only. Replaces next/head.
// static — equivalent to writing tags by hand
export const metadata = {
title: 'Shop',
description: 'Shoes, mostly',
};// dynamic — runs per route, can await data
export async function generateMetadata({ params }) {
const { slug } = await params;
const p = await getProduct(slug); // memoised: the page's call reuses this
return { title: p.name, openGraph: { images: [p.image] } };
}- Metadata merges down the tree: the root layout sets defaults (
title: { template: '%s | Shop', default: 'Shop' }), pages override - Convention files produce tags with no code:
favicon.ico,icon.png,opengraph-image.tsx(generated OG — Open Graph — image),sitemap.ts,robots.ts,manifest.ts viewport/generateViewportare separate exports for viewport and theme colour
10. next/image, next/font, next/link
next/image — <img> with responsive srcset, lazy loading, format conversion and resizing by an optimisation endpoint — Image Optimisation.
import Image from 'next/image';
import hero from './hero.jpg'; // static import: width/height inferred
<Image src={hero} alt="" priority /> // above the fold → no lazy load
<Image src="https://cdn.example.com/a.jpg" alt="" width={800} height={600} />
<Image src={url} alt="" fill sizes="(max-width: 768px) 100vw, 50vw" /> // fills parent- Remote images need
images.remotePatternsinnext.config(images.domainsis deprecated) - Width and height are required unless static import or
fill— they reserve space and prevent Cumulative Layout Shift - Next 16 defaults:
qualities: [75](otherqualityvalues are coerced to the nearest allowed),minimumCacheTTL4 hours - Self-hosted, the optimiser runs in your Node process (uses
sharp). On Vercel it’s a billed platform service.images.unoptimizedor a customloaderhands it to an image CDN instead
next/font — downloads fonts at build and self-hosts them, so the browser never calls Google; generates a size-adjusted fallback to cut layout shift — Font Loading.
// app/layout.tsx
import { Inter } from 'next/font/google'; // or next/font/local with src
const inter = Inter({ subsets: ['latin'], display: 'swap', variable: '--font-inter' });
<html lang="en-GB" className={inter.variable}>next/link — client-side navigation plus prefetching of links that enter the viewport (production only).
import Link from 'next/link';
<Link href="/shop/red-shoes">Red shoes</Link>
<Link href="/account" prefetch={false}>Account</Link>- What a prefetch fetches has changed per version. 16 rewrote it (layouts deduplicated across links, only missing parts fetched). With
partialPrefetchingit fetches the static parts of each route;prefetch={true}fetches more - Prefetches are real requests to your server and through your proxy. Counting proxy invocations or route renders counts pages nobody opened
- Programmatic navigation:
useRouter()fromnext/navigation(push,replace,refresh,back,prefetch). Read the URL withusePathname(),useSearchParams(),useParams(). All client-only
11. Environment variables
.env all environments
.env.local local overrides — gitignored. NOT loaded when NODE_ENV=test
.env.development next dev
.env.production next build / next start
.env.test tests
- Unprefixed variables are server-only. Read in a Client Component they’re
undefined— they don’t leak, they just don’t work NEXT_PUBLIC_variables are inlined into the JavaScript bundle at build time — text substitution ofprocess.env.NEXT_PUBLIC_X. Public to anyone, and frozen into that build: promote one build through staging → production and it keeps staging’s value. Dynamic lookups (process.env[name]) aren’t inlined- Server code doing request-time rendering reads
process.envat runtime, so one Docker image can serve several environments as long as only server code reads the variables serverRuntimeConfig/publicRuntimeConfigwere removed in 16 — use env vars
12. next.config.ts essentials
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
cacheComponents: true, // the caching model. THE flag to check first
partialPrefetching: true,
images: {
remotePatterns: [{ protocol: 'https', hostname: 'cdn.example.com' }],
},
async redirects() {
return [{ source: '/old-shop/:path*', destination: '/shop/:path*', permanent: true }];
}, // permanent → 308, otherwise 307
async rewrites() {
return [{ source: '/blog/:path*', destination: 'https://blog.example.com/:path*' }];
},
async headers() {
return [{ source: '/(.*)', headers: [{ key: 'X-Frame-Options', value: 'DENY' }] }];
},
output: 'standalone', // minimal server bundle for Docker
reactCompiler: true, // stable from 16, off by default
};
export default nextConfig;Others to recognise: basePath, trailingSlash, i18n (Pages Router only), serverExternalPackages, transpilePackages, cacheLife (custom profiles), cacheHandler / cacheHandlers (where caches live when self-hosting), deploymentId (version-skew protection off Vercel), output: 'export' (fully static export — no server features), turbopack (top-level from 16, was experimental.turbopack).
A request, end to end
GET /shop/red-shoes
│
├─ next.config headers / redirects
├─ proxy.ts (if matcher hits) ── may redirect, rewrite, set cookie
├─ route match: app/(store)/shop/[slug]/page.tsx params = { slug: "red-shoes" }
│
├─ STATIC SHELL? ── prerendered at build (or on first request, then cached)
│ yes → send shell HTML immediately
│
├─ SERVER RENDER (Node.js)
│ root layout → (store) layout → shop layout → page
│ Server Components run, await data
│ 'use cache' scopes → served from cache or computed + stored
│ request-time parts → rendered now, streamed into Suspense holes
│ Client Components → rendered to HTML too (SSR), and recorded as
│ "load chunk X here with these props"
│
├─ RESPONSE, one stream:
│ HTML — visible before any JS runs
│ RSC payload (inline) — the serialised server tree: elements, props
│ for client components, references to chunks
│
└─ BROWSER
HTML paints
JS for CLIENT components only downloads
React reconciles HTML with the RSC payload → HYDRATES client components
<Link>s in view → prefetch their RSC payloads
NEXT CLICK (client navigation)
fetch RSC payload only (no HTML) for segments that changed
shared layouts stay mounted; page segment swaps
What to notice: SSR (server-side rendering) and Server Components are different steps in the same request. Client Components are also rendered to HTML on the server, then hydrated — Hydration. Server Components are rendered once and never hydrated. The RSC (React Server Components) payload is what makes client navigation cheap: no HTML, just the tree diff for the segments that changed. Where this sits against SSG, SSR and ISR in general is in Rendering Strategies and Framework Rendering Modes.
Required versus optional
| Question | Answer |
|---|---|
| Does every app need a root layout? | Yes. app/layout.tsx with <html> and <body> |
| Does every route need its own layout? | No. Only the root. Nested layouts are for shared, persistent UI |
Does a route need page.tsx? | Yes to be visible — a folder without page or route isn’t a URL |
Does a component need 'use client' to use state or effects? | Yes — or to be imported by a file that has it. Same for event handlers and browser APIs |
Does a component need 'use client' to be interactive inside a client parent? | No. The directive marks the boundary; everything imported below it is client |
Does an async component need anything? | No — but only Server Components can be async |
| Do I need an API route to mutate data? | No. A Server Action. Route handlers are for external callers |
Do I need loading.tsx? | No. Without it, navigation waits for the page. Under Cache Components, request-time reads need some Suspense boundary, and loading.tsx is one |
Do I need error.tsx? | No. Falls back to the parent’s, then the default error page. Must be 'use client' if present |
Do I need generateStaticParams for [slug]? | No (previous model — paths render on demand). Under Cache Components, if present it must return ≥1 param |
Do I need proxy.ts? | No |
Do I need next.config? | No. Every option has a default |
Do I need next/image? | No. A plain <img> works; you lose the optimisation and the lint will nag |
| Do I need Vercel? | No. next start runs anywhere Node runs; some features need configuration to match — see Where it bites |
| Do I need TypeScript? | No. .tsx is the default template |
Pages Router → App Router
| Pages Router | App Router |
|---|---|
pages/index.tsx | app/page.tsx |
pages/blog/[slug].tsx | app/blog/[slug]/page.tsx |
pages/_app.tsx (global CSS, providers, persistent layout) | Root app/layout.tsx. Providers move into a 'use client' component rendered there |
pages/_document.tsx (<Html>, <Head>, <body>) | Root layout writes <html> and <body> directly |
getLayout per-page pattern | Nested layout.tsx |
getServerSideProps | async Server Component that reads cookies()/headers() or uncached data |
getStaticProps | async Server Component with cached data — 'use cache', or (previous model) a static route |
getStaticProps + revalidate: 60 | cacheLife(...), or (previous model) export const revalidate = 60 |
getStaticPaths | generateStaticParams |
fallback: false / true / 'blocking' | dynamicParams = false / true (previous model). Cache Components: unlisted params render on request; notFound() to reject |
getInitialProps | Nothing. Fetch in the component |
res.revalidate('/path') (on-demand ISR) | revalidatePath / revalidateTag |
pages/api/x.ts — (req, res) Node-style | app/api/x/route.ts — GET(request) → Response |
next/router — useRouter() with pathname, query, events | next/navigation — useRouter() (no pathname, query, events), usePathname(), useSearchParams(), useParams() |
router.events (route-change analytics) | No equivalent. An effect on usePathname() + useSearchParams() |
next/head | metadata / generateMetadata |
pages/404.tsx, pages/500.tsx, _error.tsx | not-found.tsx, error.tsx, global-error.tsx |
middleware.ts | proxy.ts — shared by both routers |
| Everything is a Client Component (SSR + hydrate all) | Server by default |
Coexisting during migration — app/ and pages/ run side by side, migrated route by route:
- Navigating between routers is a hard navigation — full page load, client state lost — and
next/linkdoesn’t prefetch across. Migrate clusters of routes users move between together (all of checkout, not one step of it) - The root layout doesn’t apply to
pages/*, and_app/_documentdon’t apply toapp/*. Global CSS, fonts, analytics snippets and providers have to exist in both until the last page moves. Keep_appand_documentuntil then - The same URL in both is an error (“Conflicting app and page file”). Delete the
pages/file in the same commit that adds theapp/one [CHECK: whether this still fails the build in 16.x or only warns in dev — not found in the current migration docs] next/routerisn’t supported underapp/. Components shared by both routers useuseRouterfromnext/compat/router(returnsnullin the App Router), or take what they need as props- Context set in
_appdoesn’t reach App Router pages — a cart provider has to be mounted in both trees, and they’re separate React roots, so state isn’t shared across the hard navigation either - Caching semantics differ per router.
'use cache',revalidateTagprofiles and Cache Components apply toapp/.pages/keepsgetStaticProps/ISR semantics - The App Router runs React canary builds bundled with Next.js;
pages/uses thereactyou installed. Usually invisible; occasionally a behaviour differs between the two halves of one app - Codemods (
npx @next/codemod) handle mechanical upgrades like asyncparamsandmiddleware→proxy; they don’t migrate data fetching
The kitchen sink
Every export a page can have, at once. No real page has all of these. Cache Components mode — so no revalidate, dynamic or dynamicParams.
// app/shop/[slug]/page.tsx
import { Suspense } from 'react';
import { notFound } from 'next/navigation';
import { cacheLife, cacheTag } from 'next/cache';
export async function generateStaticParams() { // prerender these at build
return (await topProducts()).map((p) => ({ slug: p.slug }));
}
export async function generateMetadata({ params }) { // <title>, OG tags
const p = await getProduct((await params).slug);
return { title: p?.name ?? 'Not found' };
}
export const viewport = { themeColor: '#000' }; // viewport/theme meta
export const maxDuration = 30; // function timeout, seconds (platform-dependent)
async function getProduct(slug: string) {
'use cache';
cacheLife('hours');
cacheTag('products', `product-${slug}`);
return db.product.find(slug);
}
export default async function Page({ params, searchParams }) {
const { slug } = await params;
const product = await getProduct(slug);
if (!product) notFound(); // → nearest not-found.tsx
return (
<>
<h1>{product.name}</h1>
<Suspense fallback={<p>Checking stock…</p>}>
<Stock sku={product.sku} /> {/* request-time */}
</Suspense>
</>
);
}Plus, beside it: layout.tsx, loading.tsx, error.tsx, not-found.tsx, opengraph-image.tsx, actions.ts, and any 'use client' components.
One complete small app
A product listing, a product page with add-to-basket, and a stock API. Cache Components on.
shop/
├── next.config.ts
├── proxy.ts
├── .env.local DATABASE_URL=… NEXT_PUBLIC_GA_ID=G-XXXX
└── app/
├── layout.tsx root: <html>, font, header with basket count
├── page.tsx / → redirect to /shop
├── not-found.tsx
├── lib/
│ ├── db.ts import 'server-only'
│ └── products.ts cached reads
├── shop/
│ ├── page.tsx /shop — cached product grid
│ └── [slug]/
│ ├── page.tsx /shop/:slug
│ ├── actions.ts 'use server' — addToBasket
│ ├── add-to-basket.tsx 'use client' — the form
│ └── error.tsx 'use client'
└── api/stock/[sku]/route.ts GET → JSON, for a partner feed
// next.config.ts
import type { NextConfig } from 'next';
export default {
cacheComponents: true,
partialPrefetching: true,
images: { remotePatterns: [{ protocol: 'https', hostname: 'cdn.example.com' }] },
} satisfies NextConfig;// proxy.ts — tag every visitor with an anonymous ID for basket + experiment assignment
import { NextResponse, type NextRequest } from 'next/server';
export function proxy(request: NextRequest) {
const res = NextResponse.next();
if (!request.cookies.has('vid')) {
res.cookies.set('vid', crypto.randomUUID(), { httpOnly: true, sameSite: 'lax', maxAge: 60 * 60 * 24 * 365 });
}
return res;
}
export const config = { matcher: ['/((?!_next/|api/|favicon.ico).*)'] }; // skip assets// app/lib/products.ts
import 'server-only';
import { cacheLife, cacheTag } from 'next/cache';
import { db } from './db';
export async function listProducts() {
'use cache';
cacheLife('hours');
cacheTag('products');
return db.product.findMany({ orderBy: { name: 'asc' } });
}
export async function getProduct(slug: string) {
'use cache';
cacheLife('hours');
cacheTag('products', `product-${slug}`);
return db.product.findUnique({ where: { slug } });
}// app/layout.tsx
import { Suspense } from 'react';
import { cookies } from 'next/headers';
import Link from 'next/link';
import { Inter } from 'next/font/google';
import { db } from './lib/db';
const inter = Inter({ subsets: ['latin'], display: 'swap' });
export const metadata = { title: { template: '%s | Shop', default: 'Shop' } };
async function BasketCount() {
const vid = (await cookies()).get('vid')?.value; // request-time
const n = vid ? await db.basketItem.count({ where: { vid } }) : 0;
return <span>Basket ({n})</span>;
}
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en-GB" className={inter.className}>
<body>
<header>
<Link href="/shop">Shop</Link>
<Suspense fallback={<span>Basket</span>}><BasketCount /></Suspense>
</header>
{children}
</body>
</html>
);
}// app/page.tsx
import { redirect } from 'next/navigation';
export default function Home() { redirect('/shop'); }// app/not-found.tsx
export default function NotFound() { return <p>We couldn't find that.</p>; }// app/shop/page.tsx
import Link from 'next/link';
import Image from 'next/image';
import { listProducts } from '../lib/products';
export const metadata = { title: 'All products' };
export default async function Shop() {
const products = await listProducts(); // cached → in the static shell
return (
<ul>
{products.map((p) => (
<li key={p.slug}>
<Link href={`/shop/${p.slug}`}>
<Image src={p.imageUrl} alt="" width={300} height={300} />
{p.name} — £{(p.pricePence / 100).toFixed(2)}
</Link>
</li>
))}
</ul>
);
}// app/shop/[slug]/page.tsx
import { notFound } from 'next/navigation';
import { getProduct, listProducts } from '../../lib/products';
import { AddToBasket } from './add-to-basket';
export async function generateStaticParams() {
return (await listProducts()).slice(0, 50).map((p) => ({ slug: p.slug }));
}
export async function generateMetadata({ params }: PageProps<'/shop/[slug]'>) {
const p = await getProduct((await params).slug);
return { title: p?.name ?? 'Not found' };
}
export default async function Product({ params }: PageProps<'/shop/[slug]'>) {
const p = await getProduct((await params).slug);
if (!p) notFound();
return (
<article>
<h1>{p.name}</h1>
<p>£{(p.pricePence / 100).toFixed(2)}</p>
<AddToBasket sku={p.sku} />
</article>
);
}// app/shop/[slug]/actions.ts
'use server';
import { cookies } from 'next/headers';
import { refresh } from 'next/cache';
import { db } from '../../lib/db';
export async function addToBasket(_prev: { error?: string }, formData: FormData) {
const vid = (await cookies()).get('vid')?.value;
if (!vid) return { error: 'Please enable cookies' }; // the action is a public endpoint
const sku = String(formData.get('sku'));
const qty = Number(formData.get('qty') ?? 1);
if (!Number.isInteger(qty) || qty < 1) return { error: 'Quantity must be at least 1' };
await db.basketItem.create({ data: { vid, sku, qty } });
refresh(); // basket count is uncached → re-render it
return {};
}// app/shop/[slug]/add-to-basket.tsx
'use client';
import { useActionState } from 'react';
import { addToBasket } from './actions';
export function AddToBasket({ sku }: { sku: string }) {
const [state, action, pending] = useActionState(addToBasket, {});
return (
<form action={action}>
<input type="hidden" name="sku" value={sku} />
<label>Qty <input name="qty" type="number" defaultValue={1} min={1} /></label>
{state.error && <p role="alert">{state.error}</p>}
<button disabled={pending}>{pending ? 'Adding…' : 'Add to basket'}</button>
</form>
);
}// app/shop/[slug]/error.tsx
'use client';
export default function Error({ error, retry }: { error: Error; retry: () => void }) {
return (<><p>Something went wrong.</p><button onClick={() => retry()}>Try again</button></>);
}// app/api/stock/[sku]/route.ts
import { connection } from 'next/server';
import { db } from '../../../lib/db';
export async function GET(_req: Request, { params }: { params: Promise<{ sku: string }> }) {
await connection(); // per request, never prerendered
const { sku } = await params;
const item = await db.stock.findUnique({ where: { sku } });
return Response.json({ sku, qty: item?.qty ?? 0 });
}What to notice: the product grid and product pages are cached and served from the static shell; only the basket count in the header runs per request, and it’s the only thing re-rendered after an add. No API route sits between the form and the database, no client fetch library, and only two small files ship as component JavaScript.
retry vs reset in error.tsx: retry() (added as unstable_retry in 16.2, stable in 16.3) re-fetches the segment from the server and re-renders — the docs’ default. reset() only clears the error state and re-renders what’s already there, so a data error just recurs. Code older than 16.3 has reset. catchError() (next/error) gives the same boundary to a component rather than a route segment.
Where it bites
Accidental client components spreading.
'use client'on a layout or a shared wrapper moves everything it imports into the bundle. Push the directive to the leaves; pass server content through aschildren- A Client Component importing a “utils” file that imports the DB client pulls server code toward the bundle —
import 'server-only'turns that into a build error rather than a runtime surprise - Third-party components that use hooks but lack
'use client'fail in a Server Component. Re-export them from a one-line'use client'file
Serialisation across the boundary.
- ORM results with
Decimal, class instances or methods fail to serialise or arrive as plain objects. Map to plain data before passing to a Client Component - Everything passed as a prop is in the HTML, readable in view-source. Passing a whole user record to render the name ships the email, the hash, the flags. Pass the fields you need — Next’s data-security docs suggest a DTO (data transfer object) layer
- Functions can’t cross unless they’re Server Actions
Caching surprises.
- Previous model: “fetch isn’t cached” ≠ “page is dynamic”. No request-time API → prerendered at build → today’s prices frozen into HTML until a deploy or revalidate
- Next 14 code upgraded to 15+ silently lost fetch caching and GET route-handler caching — more database load, not wrong data. The reverse migration (15 → Cache Components) can surface every unmarked fetch as a build error
- Calling
cookies()once in a shared layout made every route under it dynamic in the previous model. Under Cache Components it’s contained by the nearest Suspense — or flagged as blocking if there isn’t one revalidateTagserves stale to the next visitor. A user who edits and immediately reloads sees the old version. UseupdateTagin the action- Cache Components keeps routes alive in
<Activity>. Dropdowns stay open, form values anduseActionStatemessages persist when navigating back — reset explicitly 'use cache'defaults to in-memory per instance. On serverless or multiple containers, that’s close to no cache.'use cache: remote'plus a configured handler for anything that needs to survive'use cache'with nocacheLifegetsdefault(revalidate 15 min) — rarely what anyone chose deliberately
fetch in server vs client.
- A
fetchin a Server Component goes server → API; it can use secrets and internal hostnames. The same line in a Client Component goes browser → API, needs CORS (cross-origin resource sharing), a public URL and no secrets - A Client Component calling your own route handler on mount to get data the parent Server Component could have fetched is the SPA waterfall reintroduced
- Under the previous model only server
fetchgets Next’s caching options.next: { revalidate }in browser code does nothing
Env var leakage.
NEXT_PUBLIC_STRIPE_SECRETis public the moment it’s built. The prefix is a publish instruction, not a conventionNEXT_PUBLIC_*values are frozen per build — the staging API URL ends up in production when one image is promoted- Server-only values passed into a Client Component as props are public too
Self-hosting vs Vercel — Vercel has the platform side.
- Works with
next start: SSR, Server Components, actions, route handlers, proxy, ISR on one instance with persistent disk,next/image(viasharp) - Needs configuring once you run more than one instance: a shared cache handler (
cacheHandler/cacheHandlers) with tag coordination, orrevalidateTagonly clears the instance that ran it; the sameNEXT_SERVER_ACTIONS_ENCRYPTION_KEYon every instance or actions fail with “Failed to find Server Action”; adeploymentIdfor version-skew protection during rolling deploys; a CDN that respects Next’sCache-Controland streaming - What Vercel does by reading the build output: global ISR purge, Skew Protection, image optimisation as a service, proxy as Routing Middleware in front of the CDN. Elsewhere you reimplement them or go without. The Adapter API (stable in 16.2) and OpenNext are the official and community routes to parity on other hosts
- Edge runtime is deprecated.
export const runtime = 'edge'warns; Cache Components doesn’t support theruntimeexport at all. Node.js is the default and the direction
Prefetching and analytics.
- Prefetches hit the proxy and render routes — counting proxy invocations or server renders as page views or experiment exposures over-counts. Count on render in the browser
- Client navigations don’t reload the page, so tag managers keyed on page load miss them. Fire page views from an effect on
usePathname(); there’s norouteChangeCompletein the App Router
Version-specific breaking changes worth recognising in old code. Sync params, searchParams, cookies(), headers() were deprecated in 15 and removed in 16 — everything is awaited. next lint removed in 16. AMP removed in 16. Parallel route slots need default.tsx in 16. Node 20.9+ minimum in 16.
Related
- Reference - React — the library underneath: hooks, Server Components at the React level, form actions. This note doesn’t re-document it
- Reference - React Router — the main alternative. Loaders and actions per route, HTTP caching, fewer framework-owned caches
- Vercel — where Next’s build output becomes infrastructure, and the A/B-testing-in-proxy pattern
- Server Components · Hydration · Streaming Responses — the rendering mechanics
- Framework Rendering Modes · Rendering Strategies · Static Generation and Revalidation — where static, dynamic and ISR sit in general
- Data Fetching Patterns · Forms in Frameworks · Routing · Component State vs Application State
- HTTP Caching · CDN Caching — the caches outside Next’s own
- Code Splitting · Image Optimisation · Font Loading · Cumulative Layout Shift — what
next/*components are automating - Progressive Enhancement — what Server Action forms give you before JavaScript loads
- Choosing a Framework