0
0
NextJSframework~15 mins

Catch-all routes with [...param] in NextJS - Deep Dive

Choose your learning style9 modes available
Overview - Catch-all routes with [...param]
What is it?
Catch-all routes in Next.js let you create a single page that handles many different URL paths. Using the syntax [...param], you can capture multiple parts of a URL as an array. This helps when you want one page to respond to many similar routes without defining each one separately. It makes your app flexible and easier to manage.
Why it matters
Without catch-all routes, you would need to create a separate file for every possible URL path, which is hard to maintain and grows quickly. Catch-all routes solve this by grouping many paths into one handler, saving time and reducing errors. This means your website can handle complex navigation smoothly and adapt to new URLs without extra work.
Where it fits
Before learning catch-all routes, you should understand basic Next.js routing and dynamic routes with single parameters like [id]. After mastering catch-all routes, you can explore optional catch-all routes and advanced routing techniques like middleware and API routes.
Mental Model
Core Idea
Catch-all routes collect multiple URL segments into one array parameter so one page can handle many paths dynamically.
Think of it like...
Imagine a mail sorter who collects all letters addressed to any apartment in a building into one big basket labeled with the building name. Instead of sorting each apartment separately, the sorter handles all letters for that building at once.
┌───────────────┐
│ URL Path      │
├───────────────┤
│ /blog/2024/05 │
│ /blog/2024    │
│ /blog/2024/05/01 │
└─────┬─────────┘
      │
      ▼
┌─────────────────────────────┐
│ catch-all route: [...param]  │
│ param = ['blog', '2024', '05']│
│ param = ['blog', '2024']      │
│ param = ['blog', '2024', '05', '01']│
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationBasic Next.js Routing
🤔
Concept: Learn how Next.js maps files in the pages folder to URL paths.
In Next.js, each file inside the pages directory becomes a route. For example, pages/index.js is the homepage at '/', and pages/about.js is at '/about'. This simple file-to-route mapping helps you create pages quickly.
Result
Visiting '/about' loads the about.js page automatically.
Understanding this basic mapping is essential because catch-all routes build on this file-to-URL relationship.
2
FoundationDynamic Routes with Single Parameters
🤔
Concept: Next.js allows dynamic routes using square brackets to capture one URL segment as a parameter.
Create a file like pages/post/[id].js. When you visit '/post/123', Next.js passes '123' as the 'id' parameter to the page. You can access it in your component to show content based on the URL.
Result
Visiting '/post/123' shows the page with id = '123'.
This introduces the idea of dynamic routing, which catch-all routes extend to multiple segments.
3
IntermediateCatch-all Routes Syntax and Usage
🤔
Concept: Use [...param] in the filename to capture multiple URL segments as an array.
Create a file like pages/docs/[...slug].js. If you visit '/docs/a/b/c', Next.js sets slug = ['a', 'b', 'c']. Your page can then handle any number of segments under '/docs'.
Result
Visiting '/docs/a/b/c' passes slug = ['a', 'b', 'c'] to the page.
This shows how catch-all routes let one page handle many nested paths dynamically.
4
IntermediateAccessing Catch-all Parameters in Components
🤔Before reading on: do you think catch-all params are strings or arrays? Commit to your answer.
Concept: Catch-all parameters are arrays containing each part of the URL path matched.
In your page component, use useRouter() from 'next/router' or getStaticProps context to get params.slug as an array. For example, params.slug might be ['a', 'b', 'c'] for '/docs/a/b/c'. You can then render content based on this array.
Result
You can display or use each segment separately, like showing a breadcrumb navigation.
Knowing that catch-all params are arrays helps you manipulate and display nested paths easily.
5
IntermediateOptional Catch-all Routes with [[...param]]
🤔
Concept: Optional catch-all routes capture zero or more segments, allowing the route to match the base path too.
Create a file like pages/blog/[[...slug]].js. This matches '/blog', '/blog/a', '/blog/a/b', etc. If no segments are present, slug is undefined or an empty array. This lets one page handle both the base and nested paths.
Result
Visiting '/blog' and '/blog/a/b' both load the same page with different slug values.
Optional catch-all routes add flexibility by handling the base route without extra files.
6
AdvancedStatic Generation with Catch-all Routes
🤔Before reading on: do you think getStaticPaths must list every possible catch-all path? Commit to your answer.
Concept: When using static generation, you must specify all paths to pre-render with getStaticPaths, even for catch-all routes.
In getStaticPaths, return an array of params objects with slug arrays for each path you want to pre-build. For example, paths: [{ params: { slug: ['a'] } }, { params: { slug: ['a', 'b'] } }]. This ensures those pages are generated at build time.
Result
Your app pre-renders specified catch-all paths for fast loading and SEO.
Understanding this prevents build errors and ensures your dynamic pages are ready before users visit.
7
ExpertPerformance and SEO Considerations with Catch-all Routes
🤔Before reading on: do you think catch-all routes always improve SEO? Commit to your answer.
Concept: Catch-all routes can impact performance and SEO if not managed carefully, especially with many dynamic paths.
If you pre-render too many catch-all paths, build times grow. If you fallback to server rendering, initial load may be slower. Also, URLs must be meaningful for SEO. Use getStaticPaths wisely and consider fallback modes. Use canonical tags to avoid duplicate content issues.
Result
Balanced use of catch-all routes leads to good performance and SEO without excessive build times.
Knowing these trade-offs helps you design scalable, SEO-friendly Next.js apps using catch-all routes.
Under the Hood
Next.js uses the file system to map URLs to pages. When it sees a file named [...param].js, it treats any matching URL segments as an array and passes them as parameters to the page component. During build or request time, Next.js parses the URL, extracts segments, and injects them into the page props or router query. This dynamic matching happens before rendering, enabling flexible routing.
Why designed this way?
This design leverages the file-based routing system for simplicity and developer experience. Instead of complex route configuration files, developers use intuitive file names. Catch-all routes extend dynamic routing to nested paths without extra setup. Alternatives like manual route definitions would be verbose and error-prone.
┌───────────────┐
│ URL Requested │
│ /docs/a/b/c   │
└──────┬────────┘
       │
       ▼
┌───────────────────────────────┐
│ Next.js Routing Engine         │
│ - Matches pages/docs/[...slug] │
│ - Extracts slug = ['a','b','c']│
└─────────────┬─────────────────┘
              │
              ▼
┌───────────────────────────────┐
│ Page Component receives slug  │
│ - Uses slug to render content  │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does [...param] match zero URL segments or at least one? Commit to yes or no.
Common Belief:Catch-all routes with [...param] match zero or more segments, including the base path.
Tap to reveal reality
Reality:Catch-all routes with [...param] require at least one segment; they do NOT match the base path. To match zero or more, you must use optional catch-all [[...param]].
Why it matters:Confusing these causes 404 errors when expecting the base path to work, leading to broken navigation.
Quick: Do catch-all routes automatically handle all nested paths without configuration? Commit to yes or no.
Common Belief:Once you create a catch-all route, Next.js automatically handles all nested paths without extra setup.
Tap to reveal reality
Reality:For static generation, you must explicitly list all paths in getStaticPaths. Otherwise, some paths won't be pre-rendered or may cause errors.
Why it matters:Missing this causes build failures or missing pages in production, frustrating users and developers.
Quick: Can catch-all routes cause SEO problems if misused? Commit to yes or no.
Common Belief:Catch-all routes always improve SEO by covering many URLs with one page.
Tap to reveal reality
Reality:If catch-all routes serve similar content on many URLs without canonical tags, they can cause duplicate content issues hurting SEO.
Why it matters:Ignoring this can reduce search rankings and visibility, harming website success.
Quick: Are catch-all parameters always strings? Commit to yes or no.
Common Belief:Catch-all parameters are strings like single dynamic routes.
Tap to reveal reality
Reality:Catch-all parameters are arrays of strings, each representing a URL segment.
Why it matters:Treating them as strings leads to bugs when accessing or manipulating the parameters.
Expert Zone
1
Catch-all routes can be combined with middleware to pre-process or redirect based on deep URL segments, enabling powerful routing logic.
2
Using optional catch-all routes ([[...param]]) allows graceful handling of both base and nested paths in one component, reducing code duplication.
3
When using fallback: 'blocking' in getStaticPaths with catch-all routes, Next.js waits to generate pages on demand, balancing build time and user experience.
When NOT to use
Avoid catch-all routes when your app has a small, fixed set of routes that benefit from explicit files for clarity and performance. Use single dynamic routes or static routes instead. Also, if you need fine-grained control over route matching or complex patterns, consider custom server routing or middleware.
Production Patterns
In production, catch-all routes are often used for documentation sites, blogs with nested categories, or file explorers. Developers combine them with getStaticPaths for popular paths and fallback rendering for rare ones. They also use catch-all routes with API routes to handle dynamic API endpoints flexibly.
Connections
REST API Endpoint Design
Catch-all routes mimic REST APIs that use path parameters to represent nested resources.
Understanding catch-all routes helps grasp how REST APIs structure URLs to access nested data, improving backend and frontend integration.
Filesystem Hierarchy
Catch-all routes reflect how files and folders nest inside each other in a filesystem.
Knowing filesystem structures clarifies why catch-all routes capture multiple segments as arrays, similar to folder paths.
Regular Expressions
Catch-all routes behave like regex patterns matching multiple path segments dynamically.
Recognizing this connection helps understand route matching logic and how to design flexible URL patterns.
Common Pitfalls
#1Expecting [...param] to match the base path with no segments.
Wrong approach:pages/blog/[...slug].js handles '/blog' with slug undefined or empty.
Correct approach:Use pages/blog/[[...slug]].js to match '/blog' and nested paths.
Root cause:Misunderstanding that [...param] requires at least one segment, so base path is excluded.
#2Not listing all catch-all paths in getStaticPaths for static generation.
Wrong approach:export async function getStaticPaths() { return { paths: [], fallback: false }; }
Correct approach:export async function getStaticPaths() { return { paths: [ { params: { slug: ['a'] } }, { params: { slug: ['a','b'] } } ], fallback: false }; }
Root cause:Assuming catch-all routes auto-generate all paths without explicit listing.
#3Treating catch-all params as strings instead of arrays.
Wrong approach:const slug = params.slug; console.log(slug.length); // expects string length
Correct approach:const slug = params.slug; console.log(slug.length); // array length of segments
Root cause:Confusing catch-all parameters with single dynamic route parameters.
Key Takeaways
Catch-all routes in Next.js let one page handle many nested URL paths by capturing segments as an array.
The syntax [...param] requires at least one segment, while [[...param]] allows zero or more segments, including the base path.
When statically generating pages, you must list all catch-all paths explicitly in getStaticPaths to avoid missing pages.
Catch-all routes improve routing flexibility but require careful management to avoid SEO and performance issues.
Understanding catch-all routes deepens your grasp of dynamic routing, URL structure, and scalable web app design.