Next.jsMedium
What is an optional catch-all route [[...slug]]?
An optional catch-all, app/shop/[[...slug]]/page.tsx, behaves like [...slug] but also matches the parent path with no segments, so /shop, /shop/shoes and /shop/shoes/running are all handled by one file.
Values
/shopgivesparams = {}(slugisundefined)./shop/shoesgives{ slug: ["shoes"] }./shop/shoes/runninggives{ slug: ["shoes", "running"] }.
When it helps
- One page that shows "all items" at the root and filtered views deeper down.
- Docs where
/docsis the index and/docs/a/bare pages, all rendered by the same component. - Catch-all CMS routing at the root of the app:
app/[[...path]]/page.tsx, with specific routes still taking priority.
Rules
- You cannot have both
app/shop/page.tsxandapp/shop/[[...slug]]/page.tsx, because both would handle/shop. - It must be the last segment in the route.
- In
generateStaticParams, return{ slug: [] }or omitslugto prerender the root path. - Always handle the
undefinedcase;slug?.join("/") ?? ""is a common default.
Choosing between them
Use [...slug] when the root path should be a different page or a 404, and [[...slug]] when the root and deeper paths share the same UI and data logic.
Code example
tsx
1// app/shop/[[...slug]]/page.tsx2import { getProducts } from "@/lib/products";34export async function generateStaticParams() {5 return [6 { slug: [] }, // /shop7 { slug: ["shoes"] }, // /shop/shoes8 { slug: ["shoes", "running"] }, // /shop/shoes/running9 ];10}1112export default async function Shop({ params }: PageProps<"/shop/[[...slug]]">) {13 const { slug = [] } = await params; // default for /shop14 const [category, subcategory] = slug;1516 const products = await getProducts({ category, subcategory });1718 return (19 <main>20 <h1>{category ? `${category} ${subcategory ?? ""}` : "All products"}</h1>21 <p>{products.length} products</p>22 </main>23 );24}
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.