Lesson 6 of 27Routing in depth
Dynamic Routes and Static Generation
Prerender the dynamic pages that matter, serve the rest on demand, and type, validate and 404 route params properly in Next.js 16.
Your shop has 40,000 product pages under app/products/[slug]. Someone prerenders all of them at build time, and every deploy now takes 25 minutes, most of it spent on pages nobody visits. Someone else turns static generation off, and now every product view hits the database. Neither is right. This lesson is about the middle path real teams use: prerender the pages that earn it, generate the rest on demand, and make sure unknown URLs become clean 404s instead of crashes. You already know the folder syntax from App Router Routing. Here you learn what Next.js does with those folders at build time and at request time.
The params you actually get
Recall the three shapes from App Router Routing: [slug] matches one segment, [...slug] one or more, [[...slug]] zero or more. What matters now is the type each one gives you, because that is what your code has to handle.
| Folder | params type | /docs | /docs/a/b |
|---|---|---|---|
docs/[slug] | { slug: string } | no match | no match |
docs/[...slug] | { slug: string[] } | no match | ["a", "b"] |
docs/[[...slug]] | { slug?: string[] } | undefined | ["a", "b"] |
The optional catch-all is the one that bites. Forget the undefined case and slug.join("/") throws on /docs, the most visited page of the section.
You do not write these types by hand. After next dev, next build or next typegen, Next.js generates global helpers from your folder tree: PageProps<"/docs/[[...slug]]">, LayoutProps<"/docs"> and RouteContext<"/api/posts/[id]"> for Route Handlers. Rename a folder and every page that relied on the old param name fails type checking. That is the point. Turn on typedRoutes: true in next.config.ts as well and literal href values in <Link> and router.push are checked against real routes, so a typo in a link becomes a compile error instead of a 404 in production.
The types are still broad on purpose. A user can type any string into the address bar, so a [locale] param is a string, not "en" | "fr". Narrow it at the edge with a check that calls notFound():
import { notFound } from "next/navigation";
const LOCALES = ["en", "fr", "de"] as const;
type Locale = (typeof LOCALES)[number];
function assertLocale(value: string): asserts value is Locale {
if (!LOCALES.includes(value as Locale)) notFound();
}
export default async function Home(props: PageProps<"/[locale]">) {
const { locale } = await props.params; // string
assertLocale(locale); // Locale from here on
return <h1>{locale}</h1>;
}notFound() throws, so TypeScript knows nothing after the failed check runs. The rest of the file works with the narrow type.
Why params is a Promise, and where to await it
Since Next.js 15, params is a Promise, and in 16 the old synchronous access is gone. The reason is about the static shell. A page that never reads its params can be rendered once for every URL. The moment you await props.params, that part of the tree belongs to one specific URL.
So where you await decides how much of a page is shared. This matters most in layouts. If app/[category]/layout.tsx awaits params at the top, the whole layout is tied to one category and cannot be part of a generic shell. If it instead passes the Promise down to a small CategoryHeader inside a <Suspense> boundary, the layout's frame, nav and footer stay generic, and only the header waits for the param.
import { Suspense } from "react";
import { getCategory } from "@/lib/catalog";
async function CategoryHeader({ params }: Pick<LayoutProps<"/[category]">, "params">) {
const { category } = await params; // awaited inside the boundary
const data = await getCategory(category);
return <h1>{data?.name ?? "Category"}</h1>;
}
export default function CategoryLayout(props: LayoutProps<"/[category]">) {
return (
<section>
<Suspense fallback={<h1 className="skeleton">Loading</h1>}>
<CategoryHeader params={props.params} />
</Suspense>
{props.children}
</section>
);
}The rule to remember: pass the Promise down, await it as deep as you can.
generateStaticParams: choosing what to prerender
generateStaticParams runs at build time, before the page renders, and returns the list of param objects to prerender. Each object must name every dynamic segment the file is responsible for.
import { notFound } from "next/navigation";
import { getPost, getTopPostSlugs } from "@/lib/posts";
export async function generateStaticParams() {
const slugs = await getTopPostSlugs(200); // the 200 most viewed
return slugs.map((slug) => ({ slug }));
}
export default async function PostPage(props: PageProps<"/blog/[slug]">) {
const { slug } = await props.params;
const post = await getPost(slug);
if (!post) notFound();
return <article><h1>{post.title}</h1></article>;
}A few facts interviewers like to probe:
- It works in pages, layouts and Route Handlers (to prerender API responses).
- It runs once per build. During ISR revalidation it is not called again, so a new post published after the deploy is never in this list. It must be handled by on-demand generation.
fetchcalls inside it are memoized with the same calls in the page, so listing slugs and rendering pages does not double your requests. For a database client, wrap the function in React'scacheor"use cache"to get the same effect.- In
next devit runs when you visit the route, so build-time problems only show up innext build. Run a production build in CI.
Nested segments: top down or bottom up
For app/products/[category]/[product], you have two options.
Bottom up: the page returns both params in one list, { category, product }. Simple, one query.
Top down: the layout's generateStaticParams returns categories, then the page's runs once per category and receives the parent's params as a plain object (not a Promise):
export async function generateStaticParams({
params,
}: {
params: Awaited<LayoutProps<"/products/[category]">["params"]>;
}) {
const products = await getPopularProducts(params.category, 5);
return products.map((p) => ({ product: p.slug }));
}A segment can generate params for itself and segments above it, never below. A layout at [category] cannot list products.
Here is the arithmetic of top down. Each category multiplies the work, which is why "prerender everything" explodes so quickly.
Press Run (⌘ Enter) to see what happens.What does this print?
const cats = [{ category: "tops" }, { category: "shoes" }];
const perCat: Record<string, string[]> = {
tops: ["tee", "polo", "overshirt"],
shoes: ["runner", "boot"],
};
let calls = 0;
const out = cats.flatMap((c) => {
calls++;
return perCat[c.category].slice(0, 2).map((p) => ({ ...c, product: p }));
});
console.log(calls, out.length);What happens to params you did not list
This is where Next.js 16 behaves differently depending on whether Cache Components is on, and you will meet both kinds of app at work.
Without Cache Components (the 13 to 15 model)
The route segment config dynamicParams decides:
dynamicParams = true(default): an unlisted slug is rendered on the first request, then cached and served statically to everyone after. This is classic ISR.dynamicParams = false: only listed params exist. Anything else is a 404. Use it for a closed set, like a fixed list of docs versions.
With Cache Components
dynamicParams is not available. Instead, the build validates your route using the params you list, so generateStaticParams must return at least one param. An empty array is a build error. (Older code returned [] to mean "generate everything on demand". That trick no longer works here.)
For unlisted params, the model since 16.3 with partialPrefetching: true is the App Shell. At build time, alongside the listed pages, Next.js renders each dynamic route once with await params suspended. Everything outside your Suspense boundaries, plus their fallbacks, becomes a generic shell for that route.
overshirt was not returned by generateStaticParams, but tops was.
This is the Cache Components version of Pages Router fallback: true. If you want the old fallback: "blocking" behaviour, where the first visitor waits for the complete page and never sees a fallback, Next.js 16.4 adds the segment config ensureStatic = "navigation", which makes the first request for an unlisted param wait for the full static result. It also requires generateStaticParams to return complete param sets, and it fails the build if anything in the route reads uncached data or request data. Check the docs for the exact rules on your version; these APIs are new.
One subtle point about links. With Partial Prefetching, a default <Link> prefetches only the shared App Shell, which all products share. To have a link prefetch the product-specific content too (and trigger the background upgrade before the click), give it prefetch={true}. Use that on the handful of links people are likely to click, not on a grid of 200.
Unknown params and notFound()
Without dynamicParams = false, nothing stops a visitor requesting /blog/does-not-exist. Your data layer is the source of truth. Look the record up and call notFound() when it is missing, as in the blog example above. That renders the nearest not-found.tsx with a 404 status.
Two mistakes to avoid:
- Rendering an empty page with status 200.
if (!post) return <p>Not found</p>looks fine to a human, but search engines index it as a real page, and the cache may store it. Always callnotFound(). - Catching it by accident.
notFound()throws a special error. Wrapping the lookup and the call in onetry/catchswallows it. Do the fetch insidetry, and callnotFound()after the block.
generateMetadata and the page share one fetch
A post page needs the post twice: once for the <title> and Open Graph tags in generateMetadata, once for the body. Write the lookup once, in your data layer, and make it cached:
import "server-only";
import { cacheLife, cacheTag } from "next/cache";
import { db } from "@/lib/db";
export async function getPost(slug: string) {
"use cache";
cacheLife("hours");
cacheTag(`post:${slug}`);
return db.post.findUnique({ where: { slug } });
}export async function generateMetadata(props: PageProps<"/blog/[slug]">) {
const { slug } = await props.params;
const post = await getPost(slug); // same cache entry as the page
if (!post) return { title: "Not found" };
return { title: post.title, description: post.summary };
}Both calls hit the same cache entry, so the database sees one query per slug, not two. When an editor updates the post, a Server Action calls updateTag with that post's tag and both the metadata and the body refresh. If you used plain fetch, request memoization would dedupe it within one render; for an ORM, "use cache" or React's cache() is what does the deduping.
Deciding how much to prerender
The senior answer is "the pages that earn it", and you can make that concrete:
- Pull a top N from analytics or the database at build time: the most viewed products, the latest 50 posts, every category page. Everything else is generated on first visit.
- Watch build time and output size. Every prerendered page is build work, storage and deploy upload. Thousands of pages nobody opens before the next deploy are pure cost.
- Prerender pages where the first visit matters most: landing pages from ads, pages that get shared on social media, anything a crawler hits often.
- Cache the data, not just the page. If
getProductuses"use cache", on-demand pages render fast too, and the upgraded page can be fully static. - Handle content created after the deploy. It is never in
generateStaticParams. On-demand generation covers it automatically, and tags let you refresh a page when its data changes.
cacheComponents: true has generateStaticParams return [] for app/blog/[slug], copied from an older tutorial. What happens?Match each requirement to the tool.
Put the life of /tops/overshirt (unlisted product, listed category) in order, with Cache Components and Partial Prefetching.
- Tap the steps below in the right order.
Coming from the Pages Router
You will see getStaticPaths in older code. The mapping: getStaticPaths becomes generateStaticParams. fallback: false becomes dynamicParams = false (classic model) or a notFound() check. fallback: true becomes Cache Components with Partial Prefetching: the Suspense fallback is the loading state, so router.isFallback disappears. fallback: "blocking" becomes awaiting params outside Suspense, or ensureStatic = "navigation" in 16.4. getStaticProps with revalidate becomes a "use cache" function with cacheLife. The Pages Router and Migrating to App Router lesson covers the full migration.
- generateStaticParams
- A function exported from a dynamic page, layout or route handler that returns the param sets to prerender at build time.
- dynamicParams
- Segment config for the classic model:
truerenders unlisted params on demand,falsemakes them 404. Not available with Cache Components. - App Shell
- The generic prerendered part of a route that does not depend on URL data, served instantly for params that were not prerendered.
- PageProps
- A global, generated type helper such as
PageProps<"/blog/[slug]">that typesparamsandsearchParamsfrom the route literal. - typedRoutes
- A
next.config.tsoption that type checks literalhrefvalues inLinkand router methods against your real routes. - ensureStatic
- A 16.4 segment config that requires part or all of a route to be static;
"navigation"makes unlisted params wait for complete static output. - top-N prerendering
- Building only the most visited pages ahead of time and generating the long tail on first request.