Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js Dynamic Routes: Catch-All Segments and generateStaticParams

params is a Promise in Next.js 15+, catch-all arrays index differently at the root, and dynamicParams decides whether an unknown slug is prerendered or 404s.

~4 min readNext.js
#Next.js#App Router#Routing#SSG
3D illustration of URL path segments with a bracket slot receiving parameter tiles and prerendered pages

Quick Summary

A dynamic segment is a folder whose name is in brackets: app/blog/[slug]/page.tsx matches /blog/anything and exposes the value as params.slug. A catch-all [...slug] matches one or more segments and gives an array; an optional catch-all [[...slug]] also matches the parent path itself. In Next.js 15 and later, params is a Promise in pages, layouts, route handlers, and generateMetadata, so the first line of every such function is await params.

generateStaticParams pre-renders a set of parameter values at build time. It returns an array of objects matching the segment names, is called at build for each dynamic segment in the path (top-down), and works with dynamicParams to decide what happens to a value that is not in the list: true (the default) renders it on demand, false returns a 404.

The pairing that matters: generateStaticParams + dynamicParams: false gives a fully static, closed set of URLs — the pattern for a CMS with a known slug list. Without generateStaticParams, the route is server-rendered on demand and the first request pays for the render. With it and dynamicParams: true, known slugs are instant and new slugs still work.

Basic Syntax & Core Signatures

tsx
// app/blog/[slug]/page.tsx type Params = { slug: string }; export async function generateStaticParams(): Promise<Params[]> { const posts = await db.post.findMany({ select: { slug: true } }); return posts.map((p) => ({ slug: p.slug })); } export const dynamicParams = false; // unknown slug -> 404 instead of on-demand render export default async function Post({ params }: { params: Promise<Params> }) { const { slug } = await params; const post = await getPost(slug); if (!post) notFound(); return <article>{post.body}</article>; }
tsx
// app/docs/[...path]/page.tsx — catch-all, params.path is string[] export default async function Doc({ params }: { params: Promise<{ path: string[] }> }) { const { path } = await params; // ["guides", "deploy"] return <DocView segments={path} />; } // app/shop/[[...filters]]/page.tsx — optional catch-all: also matches /shop // /shop -> filters === undefined // /shop/sale/men -> filters === ["sale", "men"]
tsx
// Nested dynamic segments: generate the parent, then the child // app/blog/[slug]/[commentId]/page.tsx export async function generateStaticParams({ params, }: { params: { slug: string }; // the parent's params, already resolved }) { const comments = await db.comment.findMany({ where: { postSlug: params.slug } }); return comments.map((c) => ({ commentId: c.id })); }
tsx
// Metadata and route handlers receive the same Promise export async function generateMetadata({ params }: { params: Promise<Params> }) { const { slug } = await params; const post = await getPost(slug); return { title: post?.title ?? "Not found" }; } // app/api/posts/[id]/route.ts export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) { const { id } = await params; return Response.json(await db.post.findUnique({ where: { id } })); }

Key Comparison Table

SegmentMatchesparams value
[slug]Exactly one segment{ slug: "hello" }
[...slug]One or more segments{ slug: ["a", "b"] }
[[...slug]]Zero or more segments{ slug: undefined } or array
SettingValueEffect on an unknown param
generateStaticParams present—Listed values prerendered at build
dynamicParamstrue (default)Unknown value rendered on first request
dynamicParamsfalseUnknown value returns 404
Neither—Every request renders on the server
dynamic = "force-static"—Params must be listed; no on-demand render
SymptomMeaning
params.slug is undefinedawait params missing, or the folder name and type disagree
404 for a valid slugdynamicParams: false and the slug is not in generateStaticParams
Build tries to prerender thousands of pagesReturn a subset; leave the rest to on-demand
generateStaticParams runs at runtimeRoute is dynamic (cookies() in the tree)

Practical Edge Cases & Deep Dives

1. Awaiting params is mandatory in Next.js 15+

tsx
// Next.js 14 style — broken in 15+ export default function Page({ params }: { params: { slug: string } }) { return <div>{params.slug}</div>; // params.slug is now a Promise property access }

The migration is mechanical: mark the function async, type the prop as Promise<…>, and await it. The same change applies to searchParams in pages and to the second argument of route handlers. Code that reads params synchronously still compiles in TypeScript only if you cast; at runtime it logs the "params should be awaited" error and the value is undefined.

2. generateStaticParams and a large catalogue

Returning 50,000 slugs from generateStaticParams means 50,000 pages at build time, a build that runs for hours, and a deploy that fails on memory. The practical pattern for large catalogues is to prerender the popular subset and let the rest render on demand into the cache:

tsx
export async function generateStaticParams() { return db.product .findMany({ where: { featured: true }, select: { slug: true }, take: 500 }) .then((rows) => rows.map((r) => ({ slug: r.slug }))); } export const dynamicParams = true; // the other 49,500 render on first request

On a self-hosted Next.js server the on-demand render is written to the cache and served statically afterwards; on a platform with static output it may be generated per request instead, which is worth checking before assuming an ISR-like cost.

3. Catch-all arrays, empty optional segments, and the trailing slash

text
/blog/a/b -> [...slug].slug = ["a", "b"] /blog -> no match for [...slug]; matches [[...slug]] with slug undefined /docs/ -> [[...slug]].slug = [] (empty array) or undefined depending on version

The empty-array case is the one that breaks code: const last = slug[slug.length - 1] is undefined at the root path. Guard with Array.isArray(slug) && slug.length > 0 — and treat an empty array and undefined as the same "no filter" state.

4. notFound() versus an empty page

tsx
const post = await getPost(slug); if (!post) notFound(); // renders the nearest not-found.tsx, status 404

notFound() throws a special error that the framework catches: the response is a 404 and app/not-found.tsx renders. Returning null instead produces a 200 with an empty page, which search engines index and users report as broken. In a route handler, notFound() also works and returns a 404 with the rendered boundary.

5. Generating params from a CMS and keeping them fresh

generateStaticParams runs at build time unless the route is revalidated. A CMS publishing a new slug after deployment will 404 when dynamicParams: false — the fix is either to rebuild on publish (a webhook) or to allow on-demand rendering:

tsx
export const revalidate = 300; // ISR: re-render at most every 5 minutes export const dynamicParams = true; // new slugs work without a rebuild

With revalidate, the page's data is refreshed in the background and the stale version is served until the new one is ready. Pair it with tag-based invalidation (revalidateTag) when the CMS webhook should make a change appear immediately rather than within the window.

Common Runtime & Configuration Mistakes

SymptomCauseFix
params undefined at runtimeNot awaitedawait params
404 on a new CMS slugdynamicParams: falseSet true or rebuild on publish
Build time explodedToo many static paramsPrerender a subset
Catch-all crashes at the root pathEmpty array indexingGuard slug?.length
generateStaticParams returns nothing, pages 404Returned shape does not match folder namesReturn { slug } matching [slug]
200 with a blank pageReturned null instead of notFound()Call notFound()
Metadata missing on dynamic pagesStatic metadata export onlyUse generateMetadata with awaited params
Route handler params typed as an objectNext.js 14 typingPromise<{ id: string }>
Search params missingsearchParams also a Promise in 15+Await it in the page
Same page rendered per request unexpectedlycookies() or headers() in the treeMove them behind Suspense

A dynamic route is a mapping from URL segments to a parameter object, and everything else follows from three choices: how many segments it accepts, which values are known at build, and what happens to the rest.

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.