Dynamic Segments, Catch-Alls, and generateStaticParams
A blog has two thousand posts and one page component. A documentation site has a thousand guides and one layout. That ratio â many URLs, one file â is the entire reason dynamic routes exist, and the App Router expresses it with folder names rather than configuration. Put square brackets around a folder name and that folder accepts any value for that segment; the value arrives in your component as data instead of as a separate file you had to write.
By the end of this lesson you will be able to read a bracketed folder name and predict exactly which URLs it matches, choose between a single segment, a catch-all, and an optional catch-all, decide whether params needs awaiting, and pre-render a known set of dynamic pages at build time with generateStaticParams.
Prerequisites
- !App Router folder conventions: page.js, layout.js and route segments
- !Reading and writing async JavaScript functions
- !A local Next.js project you can start with npm run dev
What You'll Learn
- 1Map a bracketed folder name to the exact URLs it accepts
- 2Pass params safely into Server Components across Next.js versions
- 3Pick between [param], [...slug] and [[...slug]] for a given data shape
- 4Pre-render a known set of dynamic pages and control unknown ones
The folder name is the URL pattern
There is no route table to edit. When you create app/blog/[slug]/page.js, Next.js derives the pattern from the path: blog is a literal segment, [slug] is a placeholder that matches exactly one path segment. The URL /blog/launch-notes renders that file with slug set to launch-notes. A path with two segments after blog, such as /blog/2024/launch-notes, does not match at all â the segment count is part of the pattern, not a suggestion.
Matching is also strict about what counts as a segment. Slashes split segments, so slug never contains a slash. If you need slashes inside the matched value, you need a catch-all route instead. And an empty segment does not match: /blog/ with nothing after it resolves to the app/blog/page.js index route, or to a 404 if you never wrote one.
// app/blog/[slug]/page.js
import { notFound } from 'next/navigation';
import { getPost, getAllPosts } from '@/lib/posts';
// Tell Next.js which slugs exist so they can be rendered at build time.
export async function generateStaticParams() {
const posts = await getAllPosts();
return posts.map((post) => ({ slug: post.slug }));
}
export default async function BlogPost({ params }) {
const post = await getPost(params.slug);
// A slug that exists in the URL but not in the data is a 404, not an error.
if (!post) notFound();
return (
<article>
<h1>{post.title}</h1>
<time dateTime={post.publishedAt}>{post.publishedAt}</time>
<div>{post.body}</div>
</article>
);
}
Two habits in that file are worth copying. The page returns every parameter key the folder defines â one key per bracketed folder, so app/[category]/[id]/page.js yields both category and id. And a missing record calls notFound() instead of throwing, which routes the request into your not-found.js UI and keeps the stack trace out of the user's face.
params is a plain object in one version and a Promise in the next
This is the single most common source of runtime breakage when a project upgrades. Next.js 14 hands your page a plain object, so params.slug reads directly. Next.js 15 and later make params a Promise, because route data is resolved alongside other async request APIs such as cookies() and headers(). Reading params.slug without awaiting it gives you undefined, and the failure is silent until something downstream tries to use it.
The safe pattern that works in both worlds is to await it:
// app/products/[category]/[id]/page.js
export default async function ProductPage({ params }) {
// Works on 15+; on 14 awaiting a plain object simply returns the object.
const { category, id } = await params;
const product = await getProduct(category, id);
if (!product) notFound();
return <ProductDetails product={product} />;
}
Client Components receive params as props too, but only through a wrapper such as useParams() from next/navigation, never as a direct prop on a page. Keep in mind that whatever you pass from a Server Component to a Client Component must be serializable â you cannot ship the record itself if it contains functions or class instances, so pass the id and fetch on the other side of the boundary if you need to.
Catch-all routes match the rest of the path
When the number of segments is unknown ahead of time â documentation trees, nested shop categories, share links with arbitrary depth â a single bracket cannot express it. [...slug] matches one or more trailing segments and delivers them as an array in order.
// app/docs/[...slug]/page.js
import { getDoc } from '@/lib/docs';
import { notFound } from 'next/navigation';
export default async function DocPage({ params }) {
const { slug } = await params;
// /docs/getting-started/install -> slug = ['getting-started', 'install']
const doc = await getDoc(slug.join('/'));
if (!doc) notFound();
return (
<main>
<nav>Breadcrumb: {slug.join(' / ')}</nav>
<h1>{doc.title}</h1>
<article>{doc.body}</article>
</main>
);
}
Note the array is always defined when the route matches, because a catch-all requires at least one segment. The join('/') idiom turns the array back into the path key your content layer stores.
Optional catch-all routes absorb the empty case
[[...slug]] is identical with one exception: the route also matches when zero segments remain, in which case slug arrives as undefined. That makes it the right shape for a documentation site where /docs should render a table of contents while /docs/install renders a page â one file instead of an index plus a catch-all that fight over precedence.
// app/docs/[[...slug]]/page.js
export default async function Docs({ params }) {
const { slug } = await params;
// /docs -> slug is undefined -> render the index
// /docs/install -> slug is ['install']
const path = slug ? slug.join('/') : 'index';
const node = await getDocTree(path);
return <DocShell node={node} />;
}
The cost of that flexibility is a less obvious 404 story. With an optional catch-all, a typo such as /docs/install/extra may still match and reach your component with a path you cannot resolve, so the page still has to call notFound() itself rather than relying on the router to reject the URL.
Choosing the right shape
| Route file | Example URL | Value in params | Reach for it when |
|---|---|---|---|
app/blog/[slug]/page.js | /blog/hello | slug = "hello" | Exactly one segment identifies the record |
app/[category]/[id]/page.js | /shoes/42 | category, id | Two fixed levels carry the identity |
app/docs/[...slug]/page.js | /docs/a/b | slug = ["a","b"] | Depth varies and at least one segment is required |
app/docs/[[...slug]]/page.js | /docs or /docs/a | slug undefined or array | The bare root must render too |
app/(shop)/products/page.js | /products | none | No placeholder; literal path only |
A practical tie-breaker: if you can write a regular expression for the URL, a single or multi-segment pattern will do. If the URL can be empty after the prefix, you need the optional form. If it can contain arbitrary depth including one level, catch-all covers it.
Pre-rendering a known set at build time
generateStaticParams returns an array of parameter objects, and Next.js renders one page for each entry during next build. It is what turns a dynamic route into static HTML for the paths you already know about. Returning a subset is legitimate â you can pre-render your ten most-read posts and let the rest render on demand.
// app/shop/[...slug]/page.js
export const dynamicParams = true; // default: unknown slugs render on request
export async function generateStaticParams() {
const paths = await getTopLevelPaths(); // [{ slug: ['shoes'] }, { slug: ['shoes','nike'] }]
return paths;
}
Set dynamicParams = false and the same route rejects anything generateStaticParams did not return, producing a 404 instead of hitting the server. That combination â a pre-rendered allowlist for a marketing site, an on-demand render for an authenticated dashboard â is how teams get build-time speed without losing coverage. Because this is a static build, any path that depends on cookies or the signed-in user must be marked dynamic some other way, which the caching lesson covers in detail.
How Next.js picks a winner when patterns overlap
Once several files could match a request, the router applies deterministic precedence rather than folder order. A literal segment beats a dynamic one, a dynamic segment beats a catch-all, and an optional catch-all loses to everything else that matches. So with app/page.js, app/[slug]/page.js and app/[...slug]/page.js all present, the root takes /, the single dynamic takes /anything, and only /a/b falls through to the catch-all.
This ordering is stable enough to design against, but it has one sharp edge: a static file placed under a bracketed folder still has to compete on the same rules, and a catch-all placed too high in the tree will silently swallow paths you meant for another section. When a URL renders the "wrong" page, list every file whose path could match and sort them by that precedence mentally â the answer is almost always a literal segment that should have existed but does not.
Common Mistakes
Reading params.slug without awaiting on Next.js 15+
Fix: Destructure with `const { slug } = await params`, which is also harmless on versions where params is a plain object.
Using an optional catch-all because it feels more permissive
Fix: Reach for [[...slug]] only when the bare root must render; otherwise [...slug] gives you a defined array and a free 404 on empty paths.
Returning an empty array from generateStaticParams and assuming nothing will build
Fix: An empty array pre-renders no paths for that route; combine it with dynamicParams and on-demand rendering, or drop the function.
Letting a missing record fall through as undefined
Fix: Call notFound() as soon as the lookup fails so the nearest not-found.js handles the response.
Best Practices
- Keep one parameter key per bracketed folder and destructure it immediately at the top of the component
- Pre-render the stable, high-traffic paths and render the long tail on demand
- Join catch-all arrays back to a canonical path before looking anything up
- Test the 404 branch for every dynamic route, since a URL can always outrun your data
Key Takeaways
- Bracketed folders define patterns: one segment per bracket, slashes split segments, and segment count is fixed.
- params carries one key per bracket, arrives as an array for catch-alls, and is a Promise on Next.js 15+.
- [...slug] requires at least one segment; [[...slug]] also matches the empty path and hands you undefined.
- generateStaticParams pre-renders the paths you return, while dynamicParams decides what happens to the rest.
- Overlapping patterns resolve by literalness: static beats dynamic, dynamic beats catch-all, catch-all loses last.