Next.js BasicsCore· 35 min read

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.

A dynamic route: [id] becomes params.id inside the page
// 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.

FileURL visitedparams.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?

Answer: Square brackets make a dynamic segment. app/product/[id]/page.js matches any product id and exposes it as params.id.

✍️ Practice

  1. Create app/users/[id]/page.js and show the id on the page for /users/5.
  2. Make a /blog list page with three <Link>s pointing to /blog/1, /blog/2 and /blog/3.

🏠 Homework

  1. Build a dynamic /product/[id] page that greets the product id, and link to three products from a list page.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →