How to Use Catch All Routes in Next.js for Dynamic Routing
In Next.js, use a file named
[...param].js inside the pages folder to create a catch all route that matches any nested path. The matched parts are available as an array in params.param inside getStaticProps or getServerSideProps.Syntax
To create a catch all route in Next.js, name your file with three dots inside square brackets like [...param].js. This file will match any route that starts with the folder path and captures all remaining parts as an array.
For example, pages/blog/[...slug].js matches /blog/a, /blog/a/b, /blog/a/b/c, etc.
Inside the page, you access the matched parts via params.slug which is an array of strings.
javascript
pages/blog/[...slug].js export default function BlogPost({ slug }) { return <div>Slug parts: {slug.join(' / ')}</div>; } export async function getStaticProps({ params }) { return { props: { slug: params.slug || [] } }; } export async function getStaticPaths() { return { paths: [], fallback: 'blocking' }; }
Example
This example shows a catch all route that displays all parts of the URL path after /docs. It uses getStaticProps to get the path parts and renders them joined by slashes.
javascript
pages/docs/[...params].js export default function DocsPage({ params }) { return <main> <h1>Docs Path</h1> <p>You are at: /docs/{params.join('/')}</p> </main>; } export async function getStaticProps({ params }) { return { props: { params: params.params || [] } }; } export async function getStaticPaths() { return { paths: [], fallback: 'blocking' }; }
Output
<main>
<h1>Docs Path</h1>
<p>You are at: /docs/a/b/c</p>
</main>
Common Pitfalls
- Not using three dots
[...param]but only one[param]which matches only one segment, not all nested paths. - For optional catch all routes, use
[[...param]].jsto also match the base path without extra segments. - For
getStaticPaths, forgetting to returnfallback: 'blocking'orfalsecan cause build errors or missing pages. - Accessing
params.paramas a string instead of an array causes bugs.
javascript
/* Wrong: matches only one segment */ // pages/blog/[slug].js /* Right: matches all nested segments */ // pages/blog/[...slug].js
Quick Reference
| Pattern | Matches | Notes |
|---|---|---|
| [param].js | /a | Matches exactly one segment |
| [...param].js | /a, /a/b, /a/b/c | Matches all nested segments as array |
| [[...param]].js | Base path and nested paths | Optional catch all route, matches zero or more segments |
Key Takeaways
Use
[...param].js to catch all nested routes as an array in Next.js.Access the matched segments via
params.param inside data fetching methods.Use
[[...param]].js for optional catch all routes that include the base path.Always set
fallback in getStaticPaths to handle dynamic paths properly.Catch all routes simplify handling deeply nested dynamic URLs with one file.