Blog>
Snippets

Dynamic Nested Routes Handling

Exemplify how to handle nested dynamic routes in Next.js by structuring folders and files to match the desired URL scheme, including a combination of static and dynamic segments.
// pages/products/index.js
export default function Products() {
  // This component would render the list of products.
  return <p>Here is a list of products.</p>;
}
This code represents a page that lists all products. The file is located in the 'pages/products' directory, corresponding to the '/products' route.
// pages/products/[id].js
import { useRouter } from 'next/router';

export default function Product() {
  const router = useRouter();
  const { id } = router.query;
  // Fetch product details using the 'id' parameter
  return <div>Details about product {id}</div>;
}
This code defines a dynamic route for individual products. The file is named '[id].js' inside the 'pages/products' folder, handling any route like '/products/1', '/products/2', etc., with 'id' being the dynamic segment.
// pages/products/[id]/reviews/index.js
export default function Reviews() {
  // This component would render the list of reviews for a product.
  return <p>Here are reviews for the product.</p>;
}
This page shows reviews for a specific product. The file path 'pages/products/[id]/reviews/index.js' corresponds to the route '/products/:id/reviews', where ':id' is a placeholder for the actual product ID.
// pages/products/[id]/reviews/[reviewId].js
import { useRouter } from 'next/router';

export default function Review() {
  const router = useRouter();
  const { id, reviewId } = router.query;
  // Use 'id' and 'reviewId' to fetch the specific review of the product
  return <div>Review {reviewId} for product {id}</div>;
}
This code is for a nested dynamic route displaying a specific review of a product. The file 'pages/products/[id]/reviews/[reviewId].js' matches the route '/products/:id/reviews/:reviewId', with ':id' and ':reviewId' as dynamic segments.
// pages/products/[...all].js
import { useRouter } from 'next/router';

export default function CatchAll() {
  const router = useRouter();
  const { all } = router.query;
  // The array 'all' will contain all the segments of the URL
  return <div>Catch all route segments: {JSON.stringify(all)}</div>;
}
This code snippet handles all undefined routes under '/products' using a catch-all route. The file 'pages/products/[...all].js' will match any other sub-routes under '/products' not explicitly defined by other pages.