Dynamic Routes
Dynamic routes let you create pages that can display different content based on URL parameters. Think of them as templates that adapt to the data they receive.
For example, a blog might have posts at /blog/my-first-post, /blog/second-post, etc. Instead of creating a separate file for each post, you can create one dynamic route that handles all of them.
Creating Dynamic Routes
To create a dynamic route, you use square brackets in the file or directory name. The name inside the brackets becomes a parameter that you can access in your page.
app/
โโโ blog/
โโโ [slug]/
โโโ page.js
In this example, [slug] is a dynamic segment. If a user visits /blog/hello-world, the slug parameter will be "hello-world".
Accessing Parameters
In your page component, you can access the dynamic parameters through the params prop. This object contains all the dynamic segments from the URL.
// app/blog/[slug]/page.js
export default function BlogPost({ params }) {
return (
<div>
<h1>Blog Post: {params.slug}</h1>
</div>
);
}
You can use this parameter to fetch the appropriate data. For a blog, you might fetch the post content based on the slug.
export default async function BlogPost({ params }) {
const post = await getPost(params.slug);
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
Multiple Dynamic Segments
You can have multiple dynamic segments in a single route. For example, to create a route like /blog/2024/my-post, you would use:
app/
โโโ blog/
โโโ [year]/
โโโ [slug]/
โโโ page.js
Now your page component receives both params.year and params.slug. This flexibility lets you create complex URL structures.
Catch-All Routes
Sometimes you need to match multiple path segments. Catch-all routes use the spread operator syntax: [...slug].
app/
โโโ docs/
โโโ [...slug]/
โโโ page.js
This route matches /docs/a, /docs/a/b, /docs/a/b/c, and so on. The slug parameter becomes an array of all the segments.
Catch-all routes are perfect for documentation sites, nested navigation, or any situation where the URL depth is variable.