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/intro gives slug = ["intro"].
  • /docs/guides/routing/advanced gives slug = ["guides", "routing", "advanced"].
  • /docs does not match. Use an optional catch-all [[...slug]] or a separate app/docs/page.tsx for 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]/edit is 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 call notFound() for unknown paths.

Code example

tsx
1// app/docs/[...slug]/page.tsx
2import { notFound } from "next/navigation";
3import { getDoc, getAllDocPaths } from "@/lib/docs";
4
5export async function generateStaticParams() {
6 const paths = await getAllDocPaths(); // e.g. ["guides/routing", "api/link"]
7 return paths.map((p) => ({ slug: p.split("/") }));
8}
9
10export default async function DocPage({ params }: PageProps<"/docs/[...slug]">) {
11 const { slug } = await params; // /docs/guides/routing -> ["guides", "routing"]
12
13 // Guard against "..", empty parts and odd characters before touching the file system
14 if (slug.some((part) => !/^[a-z0-9-]+$/.test(part))) notFound();
15
16 const doc = await getDoc(slug.join("/"));
17 if (!doc) notFound();
18
19 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.

Open in study app