codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
▲

Next.js

7 / 73 topics
4File System Routing5Pages Directory6Dynamic Routes7Catch All Routes
Tutorials/Next.js/Catch All Routes
▲Next.js

Catch All Routes

Updated 2026-04-20
3 min read

Catch All Routes in Next.js

Introduction

In this section, we will explore Catch All Routes, a powerful feature provided by Next.js that allows you to handle dynamic routes with an arbitrary number of segments. This is particularly useful for creating flexible and scalable applications where the route structure can vary significantly.

Understanding Catch All Routes

What are Catch All Routes?

Catch All Routes enable you to define a page that matches any number of subpaths. Unlike standard dynamic routes ([param]), which match exactly one segment, catch all routes use [...slug].js syntax and can capture multiple segments in the URL.

For example, if you have a file named [...slug].js under app/blog, it will match URLs like /blog/post-1, /blog/category/subcategory/post-2, and so on. The captured segments are available as an array in the params object.

Use Cases

  • Dynamic Blog Posts: Handling blog posts with nested categories.
  • CMS Integration: Fetching content from a CMS where the URL structure can be deeply nested.
  • E-commerce Categories: Managing products across multiple levels of categories.

Setting Up Catch All Routes

To implement catch all routes, follow these steps:

  1. Create the Catch All Route File:

    • Place a file named [...slug].js in your app directory or any subdirectory.
    • For example, to handle blog posts with nested categories, create app/blog/[...slug]/page.js.
  2. Accessing the Slug Parameter:

    • The captured segments are available as an array in the params object (params.slug).
    • You can use this array to fetch data or render content dynamically.

Example: Blog Posts with Nested Categories

Let's create a simple blog application where posts can be nested under multiple categories.

Directory Structure

/app
  /blog
    [...slug]
      page.js

Code Implementation

// app/blog/[...slug]/page.js
import { useParams } from 'next/navigation';
import React, { useEffect, useState } from 'react';

const BlogPost = () => {
  const params = useParams();
  const { slug } = params;
  const [post, setPost] = useState(null);

  useEffect(() => {
    // Simulate fetching data based on the slug
    if (slug) {
      fetchBlogPost(slug).then(setPost);
    }
  }, [slug]);

  const fetchBlogPost = async (slugArray) => {
    // Implement your logic to fetch blog post based on the slug array
    // For demonstration, we'll return a mock post object
    return {
      title: 'Sample Post',
      content: 'This is a sample blog post.',
      categories: slugArray.join(' > ')
    };
  };

  if (!post) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>{post.title}</h1>
      <p>Categories: {post.categories}</p>
      <article>{post.content}</article>
    </div>
  );
};

export default BlogPost;

Explanation

  • useParams Hook: This hook provides access to the params object, which includes the captured slug segments.
  • State Management: We use a state variable (post) to store and display the fetched blog post data.
  • Data Fetching: The fetchBlogPost function simulates fetching data based on the slug array. In a real-world application, you would replace this with an API call.

Best Practices

  1. Dynamic Imports:

    • Use dynamic imports for large components or libraries that are not needed immediately to improve performance.
  2. Error Handling:

    • Implement error handling to manage cases where the slug does not match any existing content or when data fetching fails.
  3. SEO Considerations:

    • Ensure that your catch all routes generate appropriate meta tags and titles for better SEO performance.
  4. Performance Optimization:

    • Use Next.js features like generateStaticParams for static generation where applicable to improve load times and reduce server load.

Advanced Usage

Generating Static Paths with Catch All Routes

If you want to pre-render pages at build time, you can use generateStaticParams in combination with catch all routes. This is useful for generating a list of valid slugs.

// app/blog/[...slug]/page.js
export async function generateStaticParams() {
  // Fetch the list of blog post slugs from your CMS or database
  const paths = [
    { slug: ['post-1'] },
    { slug: ['category', 'subcategory', 'post-2'] }
  ];

  return paths;
}

Explanation

  • generateStaticParams: This function returns a list of paths that should be pre-rendered. Each path object contains an array of params, which includes the captured slug segments.

Conclusion

Catch All Routes in Next.js provide a flexible way to handle dynamic routes with multiple segments. By understanding how to set up and utilize catch all routes, you can build robust applications that adapt to varying URL structures. Remember to implement best practices for error handling, performance optimization, and SEO to ensure your application is both functional and efficient.

In the next section, we will explore more advanced routing features in Next.js, including API Routes and Dynamic Imports. Stay tuned!


PreviousDynamic RoutesNext API Routes

Recommended Gear

Dynamic RoutesAPI Routes