Introduction
Next.js offers a powerful file‑based router. Beyond basic pages, you can create:
- Dynamic routes with [param].js
- Catch‑all routes with [[...param]].js
- Nested folders for route groups
- Route intercepts for advanced layouts
Dynamic Routes
Create a file at pages/products/[id].js:
export default function Product({ id }) {
return <div>Product ID: {id}</div>
}
Use getStaticPaths to pre‑render:
export async function getStaticPaths() {
const products = await fetchProducts()
return {
paths: products.map((p) => ({ params: { id: p.id } })),
fallback: false,
}
}
export async function getStaticProps({ params }) {
const product = await fetchProduct(params.id)
return { props: { product } }
}
Catch‑All Routes
For optional nested paths (e.g. /docs/a/b/c), use:
pages/docs/[[...slug]].js
In getStaticPaths, supply slug arrays:
paths: [
{ params: { slug: ['getting-started'] } },
{ params: { slug: ['advanced','hooks'] } }
]
Route Groups & Intercepts
Group routes without affecting URL:
app/(auth)/login/page.js
app/(blog)/[slug]/page.js
Intercept to mount a route into another layout:
app/dashboard/page.js
app/(dashboard)/settings/page.js
Conclusion
Mastering these patterns gives you unparalleled control over your Next.js navigation and UX.