Chapter 42 compared rendering strategies in the abstract: CSR, SSR, SSG, ISR, streaming, PPR. Chapter 48 showed how Cache Components decides, component by component, what's static and what waits for a request. This chapter puts those together in Next.js terms, then follows the app out of your editor: the configuration you set per route, metadata, runtimes, environment variables, the built-in image, font and script components, instrumentation, the build toolchain, and the ways to deploy, from Vercel to a Docker container you run yourself.
The problem: one app, every kind of page#
The reading list is growing into a real product:
- A marketing homepage and an about page that change when someone edits copy.
- A page per book,
/books/[slug]. There are 40,000 books, a few hundred of them popular. - A personal dashboard that's different for every user.
- A deployment target your company picked: maybe Vercel, maybe Kubernetes, maybe "one Docker image that runs in staging and production with different settings".
Each page wants a different strategy, and the deployment target constrains what's available. A senior engineer should be able to say, for each page, when its HTML is produced, where it's cached, what runs per request, and what that costs.
The strategies in Next.js terms#
With Cache Components, you don't pick a strategy per route. Each component's code decides, and the route's output is a mix:
| Strategy (Chapter 42 name) | How you get it in Next.js 16 with Cache Components | In the previous model (14, 15) |
|---|---|---|
| Static (SSG) | Components that complete during prerendering: no uncached data, no runtime APIs, or everything in "use cache" | The default when a route used no dynamic APIs and no uncached data |
| Dynamic (SSR) | Request-time components inside <Suspense>: uncached fetches, cookies(), headers(), searchParams, connection() | Any dynamic API, cache: "no-store", or dynamic = "force-dynamic" made the whole route dynamic |
| Streaming | Every <Suspense> boundary (and loading.tsx) streams its content when ready | Same: Suspense and loading.tsx |
| PPR | The default: a static shell plus dynamic holes in one response | Experimental flag in 14 and 15, removed in 16 |
| ISR | "use cache" with cacheLife (time-based) and tags (on demand); generateStaticParams for which params to build first | export const revalidate = 60, fetch(..., { next: { revalidate } }), revalidatePath/revalidateTag |
| CSR | Client Components fetching after hydration, or TanStack Query | Same |
The left column's main idea: the unit of decision is the component, not the route. Your book page can have a prerendered description, a cached review list that refreshes hourly, and a "you've read this" badge that streams per user, all in one response.
generateStaticParams and ISR#
For a dynamic segment like /books/[slug], generateStaticParams returns the param values to prerender at build time. You don't need all 40,000. Return the popular ones:
import { Suspense } from "react";
import { cacheLife, cacheTag } from "next/cache";
import { notFound } from "next/navigation";
export async function generateStaticParams() {
const popular = await getPopularBooks(200); // build these now, the rest on demand
return popular.map((b) => ({ slug: b.slug }));
}
export default function BookPage({ params }: PageProps<"/books/[slug]">) {
return (
<Suspense fallback={<BookSkeleton />}>
{params.then(({ slug }) => <BookDetails slug={slug} />)}
</Suspense>
);
}
async function BookDetails({ slug }: { slug: string }) {
"use cache";
cacheLife("hours");
cacheTag(`book-${slug}`);
const book = await getBookBySlug(slug);
if (!book) notFound();
return <article><h1>{book.title}</h1><p>{book.summary}</p></article>;
}That's ISR: listed pages are built ahead of time, unlisted ones are built on first visit and cached, and every page regenerates after its revalidate time (an hour, from cacheLife("hours")) or when its tag is invalidated. Since Next.js 16.3, an unlisted URL doesn't block its first visitor; they get the App Shell instantly while the page renders, and the result is cached for whoever comes next.
At build time, generateStaticParams returned dune and emma, so those two pages are prerendered in full. Next.js also builds the App Shell: the page with param-specific parts left behind Suspense fallbacks.
Three Cache Components details: returning an empty array from generateStaticParams is a build error (return at least one param). dynamicParams isn't available; params that don't exist should call notFound(). And keep await params inside a Suspense boundary, as above, so an App Shell can exist for unlisted URLs. Awaiting it at the top of the page ties the whole shell to one URL.
generateStaticParams runs at build time only. It isn't called again when pages revalidate.
connection(): "this needs a real request"#
Some code reads no request data but still must not be prerendered: a random id, the current time, a synchronous database driver, or reading a runtime environment variable on the server. await connection() from next/server marks the point after which code runs at request time. Put the component inside Suspense:
import { connection } from "next/server";
async function ServerTime() {
await connection();
return <time>{new Date().toISOString()}</time>;
}It replaced unstable_noStore() in Next.js 15, and it's not allowed inside "use cache".
Route segment config#
Pages, layouts and Route Handlers can export constants that configure their segment. In Next.js 16.4:
| Export | Values | Notes |
|---|---|---|
ensureStatic | "auto", "shell", "prefetch", "navigation", false | Next.js 16.4 Fails the build if the route isn't static at that level. Cache Components only. Chapter 48 has the details. |
prefetch | "partial", "force-disabled" | Next.js 16.3 Per-route prefetch mode. Cache Components only. |
maxDuration | seconds | The maximum execution time on platforms that enforce one. Also applies to Server Actions on that page. |
runtime | "nodejs" (default), "edge" (deprecated) | Remove it entirely with Cache Components. |
preferredRegion | e.g. "auto", "home" | Deprecated. Where a platform should run the function. |
dynamic, revalidate, fetchCache, dynamicParams | The previous model's knobs. Not available with Cache Components, where "use cache", cacheLife, Suspense and notFound() do their jobs. |
The values must be static literals the compiler can read: export const revalidate = 600 works, 60 * 10 doesn't.
Metadata#
Titles, descriptions, Open Graph tags and icons come from two exports, both Server Component only:
import type { Metadata } from "next";
// Static: an object
// export const metadata: Metadata = { title: "Reading list" };
// Dynamic: a function, with params as a Promise like the page
export async function generateMetadata({ params }: PageProps<"/books/[slug]">): Promise<Metadata> {
const { slug } = await params;
const book = await getBookBySlug(slug); // fetches are deduplicated with the page's
return {
title: book ? `${book.title} | Reading list` : "Book not found",
openGraph: { images: book?.cover ? [book.cover] : [] },
};
}A segment exports one or the other, not both. Metadata from layouts and pages merges down the tree, and generateMetadata receives a parent promise if it needs to extend it. File conventions cover the rest: icon.png, opengraph-image.tsx, sitemap.ts, robots.ts.
Since 15.2, dynamic metadata can stream: the page's UI starts without waiting for generateMetadata, and the tags arrive later in the response. Bots that execute JavaScript handle that; for bots that only read the initial HTML (Next.js keeps a list, configurable with htmlLimitedBots), Next.js waits for metadata, and with PPR it skips the static shell and renders the page at request time. The same Cache Components rules apply inside generateMetadata: uncached data there is request-time work, so cache it or accept that metadata is dynamic.
Node.js and Edge runtimes#
Next.js code on the server runs in one of two runtimes:
- Node.js (default): the full Node API, the file system, native modules, every npm package.
- Edge: a restricted runtime built on Web APIs (
fetch,Request,Response, Web Crypto, streams). No file system, no native modules, norequire, noeval, and no ISR. It was designed for running close to users with tiny cold starts.
The history matters because interviewers who used Next.js 13 remember "put it on the edge" as advice. In Next.js 16 the route-level export const runtime = "edge" is deprecated, Cache Components doesn't support the runtime export at all, and proxy.ts runs on Node.js. The old middleware.ts still runs on Edge in 16 but is deprecated too. The direction is clear: Node.js everywhere, with platforms making Node fast at the edge rather than you rewriting code for a smaller runtime.
Environment variables#
Next.js loads .env files into process.env on the server, first match wins:
- Real environment variables (
process.env) .env.$(NODE_ENV).local.env.local(skipped whenNODE_ENVistest).env.$(NODE_ENV).env
Variables are server-only unless their name starts with NEXT_PUBLIC_. Those are different in a way that bites people: next build replaces every process.env.NEXT_PUBLIC_X in client code with the literal value at build time. The browser bundle contains the string, not a lookup. So:
- Changing a
NEXT_PUBLIC_variable needs a rebuild. Setting it at container start does nothing for code already built. - Dynamic lookups like
process.env[name]aren't replaced. - Anything in a
NEXT_PUBLIC_variable is public. Never put a secret there.
Server code can read non-public variables at request time, which is how one Docker image serves staging and production. With Cache Components, call await connection() before reading, so the value isn't frozen into a prerendered page at build time:
import { connection } from "next/server";
async function FeatureFlags() {
await connection();
const flags = process.env.FEATURE_FLAGS; // read per request, not at build
return <FlagsProvider value={parseFlags(flags)} />;
}Here's a toy version of what next build does to client code with environment variables. It has a bug: run it and look at the output. Fix inlineEnv so only NEXT_PUBLIC_ variables are replaced with their values; everything else is left exactly as written.
// Replaces process.env.NAME in client code with the variable's value.
export function inlineEnv(source, env) {
return source.replace(/process\.env\.([A-Z0-9_]+)/g, (match, name) =>
name in env ? JSON.stringify(env[name]) : match,
);
}Images, fonts and scripts#
Three components exist because doing these by hand is easy to get subtly wrong.
next/image serves resized, modern-format images (WebP by default) through an optimizer, with srcset and lazy loading:
import Image from "next/image";
<Image src="/covers/dune.jpg" alt="Dune cover" width={300} height={450} sizes="(max-width: 768px) 50vw, 300px" />;width and height set the aspect ratio so the browser reserves space (no layout shift); use fill inside a positioned parent when the size comes from CSS. sizes tells the browser how wide the image will render; without it, a responsive image assumes 100% of the viewport and may download a huge file. For the LCP image, Next.js 16 deprecated priority in favor of preload (adds a <link rel="preload">), or loading="eager" if you only need to turn off lazy loading. Remote images need images.remotePatterns in the config. Next.js 16 also changed defaults: minimumCacheTTL is 4 hours, qualities is [75], and local IPs are blocked from optimization.
next/font downloads Google Fonts (or loads local files) at build time and serves them from your own domain, so there's no request to Google from the browser. It also generates a size-adjusted fallback font, so text doesn't jump when the web font arrives.
import { Inter } from "next/font/google";
const inter = Inter({ subsets: ["latin"], display: "swap" });
export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html lang="en" className={inter.className}>
<body>{children}</body>
</html>
);
}next/script loads third-party scripts with a strategy: beforeInteractive (in the root layout, before hydration, for things like consent managers), afterInteractive (the default, after some hydration), or lazyOnload (during idle time, for chat widgets and the like). onLoad and onError callbacks require a Client Component.
instrumentation.ts#
A file at the project root (or in src/) whose register() runs once when a server instance starts, before it handles requests. It's where observability goes: OpenTelemetry, error trackers.
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
await import("./instrumentation-node"); // e.g. start an OpenTelemetry SDK
}
}
export async function onRequestError(error: unknown, request: { path: string; method: string }, context: { routePath: string; routeType: string }) {
await reportToErrorTracker({ error, path: request.path, route: context.routePath, type: context.routeType });
}onRequestError (stable since 15) is called for errors in rendering, Route Handlers, Server Actions and proxy, with context saying which. instrumentation-client.ts is the browser-side counterpart that runs before your app's code.
The build: Turbopack and the React Compiler#
Next.js 16 Turbopack is the default bundler for both next dev and next build. It's written in Rust, incremental, and in 16.3 its disk cache became the default for builds as well as dev, so repeat builds reuse unchanged work. Apps with custom webpack config can opt out with next dev --webpack and next build --webpack; a custom webpack config without that flag fails the build, so you notice.
The React Compiler (Chapter 30) is a stable option since Next.js 16, off by default:
const nextConfig: NextConfig = {
reactCompiler: true, // npm install babel-plugin-react-compiler@latest
};It runs through Babel, so dev and build get slower; Next.js's reason for not enabling it by default is to gather more build performance data. An experimental Rust port that runs inside Turbopack (experimental.turbopackRustReactCompiler, 16.3) removes most of that cost. create-next-app asks whether you want the compiler and defaults to no.
Deploying#
The docs list four ways to run a Next.js app:
| Option | What you get |
|---|---|
Node.js server (next build then next start) | Every feature. You run the process (a VM, a PaaS). |
| Docker | Every feature. Usually built with output: "standalone". |
Static export (output: "export") | Plain HTML, CSS and JS for any static host. No server, so no Server Actions, no proxy.ts, no ISR, no request-time rendering. |
| Adapters | Platform-specific builds; features depend on the platform. |
Vercel builds Next.js natively: static shells go to its CDN, request-time work runs in functions, "use cache" has a platform cache handler, and after() maps to waitUntil. It's the reference platform because the same company builds both, which is also the usual critique: some features arrive there first.
Adapters Next.js 16.2 are the answer to that critique. An adapter is a module that hooks into the build, can adjust config, and turns the build output into a platform's deployment format. Set adapterPath in next.config (it left experimental in 16.2). The verified adapters, which run Next.js's test suite and live in the Next.js GitHub org, are Vercel and Bun; Netlify and Cloudflare have their own integrations and are working toward verified adapters.
Self-hosting with Docker#
output: "standalone" traces exactly which files and node_modules the server needs and writes them to .next/standalone, with a minimal server.js. It doesn't copy static assets, so you do:
FROM node:22-alpine AS build
WORKDIR /app
COPY . .
RUN npm ci && npm run build # next.config has output: "standalone"
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"] # PORT and HOSTNAME env vars set the addressStandalone output copies .env and .env.production into the folder as defaults (not .env.local); real environment variables override them, and you should delete those copies if they contain secrets.
Running more than one instance raises the questions an interviewer will ask:
- Caches are per instance by default. The ISR and
"use cache"stores live in memory and on local disk. Configure a shared cache handler (cacheHandlerfor the previous model's ISR cache,cacheHandlersfor"use cache") backed by something like Redis, and make sure tag invalidations reach every instance. - Server Action ids are encrypted per build. Set the same
NEXT_SERVER_ACTIONS_ENCRYPTION_KEYon every instance, or an action rendered by one instance fails on another. - Version skew. During a rolling deploy, an old client can hit a new server. Set
deploymentIdso assets and requests carry it; a mismatch triggers a hard navigation instead of a broken page. - Streaming through a proxy. nginx buffers responses by default, which defeats streaming. Send
X-Accel-Buffering: noor disable buffering for the app.
Run it locally (optional)#
npx create-next-app@latest reading-list --yes
cd reading-list
npm run buildThe build output lists each route and marks it static, partially prerendered or dynamic. Add a component that reads cookies() outside Suspense and build again to see the error; wrap it in <Suspense> and watch the route become partially prerendered. Then add output: "standalone" to next.config.ts, build, copy the static folders as above, and run node .next/standalone/server.js.
Pitfalls#
Check your understanding#
With Cache Components on, this page is built. For each component, say whether it ends up in the static shell, streams at request time, or causes an error.
export default function Page() {
return (
<>
<Hero />
<Suspense fallback={<p>...</p>}>
<Greeting />
</Suspense>
<Prices />
<Suspense fallback={<p>...</p>}>
<Popular />
</Suspense>
</>
);
}
function Hero() { return <h1>Reading list</h1>; }
async function Greeting() { const name = (await cookies()).get("name")?.value; return <p>Hi {name}</p>; }
async function Prices() { const res = await fetch("https://api.example.com/prices"); return <Table rows={await res.json()} />; }
async function Popular() { "use cache"; cacheLife("days"); return <List items={await getPopular()} />; }A Docker image was built with NEXT_PUBLIC_API_URL=https://staging.example.com. You start it in production with NEXT_PUBLIC_API_URL=https://api.example.com. What URL does client code use?
A teammate adds export const runtime = 'edge' to a page in a Next.js 16 app with Cache Components. What's the right call?
An interviewer asks: "We don't use Vercel. How would you deploy a Next.js 16 app on our own infrastructure, and what breaks if you're not careful?"
"How does incremental static regeneration work in Next.js 16 compared with the revalidate export you used in Next.js 13?"
Interview angle
In Next.js 16 with Cache Components, rendering strategy is decided per component, not per route. Work that completes at build time, including long-lived "use cache" results, goes into a static shell; request-time work streams behind Suspense; ISR is cacheLife plus tags, with generateStaticParams choosing which params to build first and unlisted ones getting an instant App Shell. NEXT_PUBLIC_ variables are inlined at build time, Node.js is the runtime now that route-level Edge is deprecated, Turbopack is the default bundler, and you deploy on Vercel, a Node server, a standalone Docker image, a static export or an adapter.
How do you choose between static, dynamic and ISR for a page in Next.js 16?
What's special about NEXT_PUBLIC_ environment variables?
Node.js or Edge runtime in Next.js today?
What do you need to configure to self-host Next.js across multiple instances?
With Cache Components, what happens when someone requests a dynamic page that generateStaticParams didn't list?
Recap#
- With Cache Components, strategy is per component: completed work and long-lived
"use cache"go in the static shell, request-time work streams behind Suspense, and ISR iscacheLifeplus tags, withgenerateStaticParamschoosing what to build first. - Since 16.3, unlisted params get the App Shell instantly and are upgraded to full pages in the background.
connection()marks code that needs a real request. - Route segment config in 16.4:
ensureStatic,prefetch,maxDuration, plus deprecatedruntimeandpreferredRegion.dynamic,revalidate,fetchCacheanddynamicParamsbelong to the previous model. NEXT_PUBLIC_variables are inlined at build time; server variables can be read per request. Node.js is the runtime; route-level Edge is deprecated.next/image,next/fontandnext/scripthandle sizing, self-hosted fonts and script loading;instrumentation.tssets up observability. Turbopack is the default bundler;reactCompiler: trueis stable but off.- Deploy on Vercel, a Node server, Docker with
output: "standalone", static export, or an adapter (stable in 16.2). Multiple instances need a shared cache, a shared Server Actions key and adeploymentId.
Sources#
- nextjs.org: Caching, generateStaticParams, ISR with Cache Components, connection
- nextjs.org: Route Segment Config, runtime, generateMetadata, Edge Runtime
- nextjs.org: Environment Variables, Image, Font, Script, instrumentation.js
- nextjs.org: Deploying, Self-Hosting, output, adapterPath
- nextjs.org blog: Next.js 16, Next.js 16.2, Next.js 16.3, Next.js 16.4
- Facts checked November 24, 2026.