Dynamic Routes with Slug and Catch-all Routes
Explain how to create a flexible routing system using slug and catch-all routes to capture complex or multi-part path segments in Next.js.
// pages/products/[...slug].js
import { useRouter } from 'next/router';
export default function ProductPage() {
const router = useRouter();
const { slug } = router.query;
return (
<div>
<h1>Product Page</h1>
<p>Path: {slug.join('/')}</p>
</div>
);
}
This is a Next.js page representing a catch-all route. The file is named '[...slug].js' inside the 'pages/products' directory, allowing it to match any number of sub-path segments under '/products/'. The useRouter hook is used to access the current route's parameters, and 'slug' will be an array containing the path segments due to the catch-all route.
// pages/blog/[slug].js
import { useRouter } from 'next/router';
export default function BlogPost() {
const router = useRouter();
const { slug } = router.query;
return (
<div>
<h1>Blog Post</h1>
<p>Slug: {slug}</p>
</div>
);
}
This is a Next.js page representing a single slug route. The file is named '[slug].js' inside the 'pages/blog' directory, making it suitable for paths such as '/blog/my-post'. The useRouter hook is used here as well to access the 'slug' parameter from the route, which in this case is a string corresponding to the path segment right after '/blog/'.