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.
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.
To implement catch all routes, follow these steps:
Create the Catch All Route File:
[...slug].js in your app directory or any subdirectory.app/blog/[...slug]/page.js.Accessing the Slug Parameter:
params.slug).Let's create a simple blog application where posts can be nested under multiple categories.
/app
/blog
[...slug]
page.js
// 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;
useParams Hook: This hook provides access to the params object, which includes the captured slug segments.post) to store and display the fetched blog post data.fetchBlogPost function simulates fetching data based on the slug array. In a real-world application, you would replace this with an API call.Dynamic Imports:
Error Handling:
SEO Considerations:
Performance Optimization:
generateStaticParams for static generation where applicable to improve load times and reduce server load.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;
}
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.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!