Next.jsMedium
What are catch-all routes and how do you define them?
A catch-all route matches one or more URL segments with a single file, using three dots in brackets: app/docs/[...slug]/page.tsx. The segments arrive as an array in params, for example /docs/a/b gives { slug: ["a", "b"] }.
Behavior
/docs/introgivesslug = ["intro"]./docs/guides/routing/advancedgivesslug = ["guides", "routing", "advanced"]./docsdoes not match. Use an optional catch-all[[...slug]]or a separateapp/docs/page.tsxfor that.
Typical uses
- Documentation sites and CMS pages where the path structure comes from content.
- Proxying an external API:
app/api/proxy/[...path]/route.ts. - File browsers, nested category pages, and localized slugs.
Priority
More specific routes win. With app/docs/getting-started/page.tsx and app/docs/[...slug]/page.tsx, the URL /docs/getting-started uses the static page. Static segments beat dynamic ones, and dynamic beats catch-all.
Static generation
generateStaticParams must return arrays for catch-all params: [{ slug: ["guides", "routing"] }].
Pitfalls
- A catch-all must be the last segment;
app/[...slug]/editis not allowed. - Values are URL-decoded strings; validate them before using them in file paths or queries to avoid path traversal.
- A root-level
app/[...slug]catches almost everything, so keep it as the last resort for CMS pages and callnotFound()for unknown paths.
Code example
tsx
1// app/docs/[...slug]/page.tsx2import { notFound } from "next/navigation";3import { getDoc, getAllDocPaths } from "@/lib/docs";45export async function generateStaticParams() {6 const paths = await getAllDocPaths(); // e.g. ["guides/routing", "api/link"]7 return paths.map((p) => ({ slug: p.split("/") }));8}910export default async function DocPage({ params }: PageProps<"/docs/[...slug]">) {11 const { slug } = await params; // /docs/guides/routing -> ["guides", "routing"]1213 // Guard against "..", empty parts and odd characters before touching the file system14 if (slug.some((part) => !/^[a-z0-9-]+$/.test(part))) notFound();1516 const doc = await getDoc(slug.join("/"));17 if (!doc) notFound();1819 return (20 <article>21 <p>Path: {slug.join(" / ")}</p>22 <h1>{doc.title}</h1>23 </article>24 );25}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.