Topic 31 of 47
[id] File
Overview
Dynamic routes allow you to create pages from dynamic data (like blog posts or user profiles). By wrapping a folder name in square brackets `[id]`, Next.js maps dynamic URL segments to that folder.
Syntax
tsx
// Folder structure: app/users/[id]/page.tsx
// Maps to URLs like /users/1, /users/abc
// page.tsx (Server Component by default)
export default function UserProfile({ params }: { params: { id: string } }) {
// params.id holds the dynamic segment value
return <h1>User Profile for ID: {params.id}</h1>;
}Common Pitfalls
- Dynamic segment names (the folder name inside brackets) must exactly match the property accessed on the `params` object.
- If you statically generate dynamic routes, you must use the `generateStaticParams()` function to tell Next.js which paths to pre-render at build time.
Real-World Example
Fetching dynamic data using route parameters:
example
tsx
// app/products/[slug]/page.tsx
export default async function ProductPage({ params }: { params: { slug: string } }) {
// 1. Await data fetching using the dynamic param
const product = await db.getProductBySlug(params.slug);
if (!product) {
return <h1>Product not found</h1>;
}
// 2. Render UI
return (
<div>
<h1>{product.name}</h1>
<p>{product.price}</p>
</div>
);
}