Dynamic Routes
One file can serve many pages — like /blog/1, /blog/2, /blog/hello — using a route with a parameter.
What you will learn
- Create a dynamic route with square brackets
- Read the parameter with params
- Build a detail page from an id
The problem: too many pages to write
Imagine a blog with 500 posts. You would never make 500 folders by hand. Instead you make one folder whose name is a placeholder, and it serves all of them. This is a dynamic route.
Square brackets make a placeholder
A folder named with square brackets, like [id], matches any value in that part of the URL. So app/blog/[id]/page.js handles /blog/1, /blog/2, /blog/hello and so on.
// app/blog/[id]/page.js
export default function PostPage({ params }) {
return (
<main>
<h1>Blog post #{params.id}</h1>
<p>You are reading post {params.id}.</p>
</main>
);
}Note: Output (visiting /blog/42): Blog post #42 You are reading post 42. Next.js read "42" from the URL and passed it in as params.id. The same single file would show "7" for /blog/7.
| File | URL visited | params.id |
|---|---|---|
app/blog/[id]/page.js | /blog/1 | "1" |
app/blog/[id]/page.js | /blog/99 | "99" |
app/blog/[id]/page.js | /blog/hello | "hello" |
The name inside the brackets becomes the key on params. Name the folder [slug] and you read params.slug instead.
Watch out: The value in params is always a string, even for /blog/42 where params.id is "42", not the number 42. Convert it with Number(params.id) if you need to do maths.
Tip: Combine dynamic routes with a list page: /blog shows all posts as <Link>s, and each link points to /blog/[id]. You will do exactly this in the final project.
Q. You want one file to handle /product/1, /product/2, etc. What do you name the folder?
✍️ Practice
- Create
app/users/[id]/page.jsand show the id on the page for/users/5. - Make a
/bloglist page with three<Link>s pointing to/blog/1,/blog/2and/blog/3.
🏠 Homework
- Build a dynamic
/product/[id]page that greets the product id, and link to three products from a list page.