Next.js Dynamic Routes
A dynamic route is one page file for many addresses. Square brackets in the folder name mark the changing part.
The staged page shows the first book
This staged page reads no params yet. It always shows the first book, Dune.
const books = [
{ id: "1", title: "Dune", author: "Frank Herbert" },
{ id: "2", title: "Pride and Prejudice", author: "Jane Austen" },
{ id: "3", title: "The Hobbit", author: "J. R. R. Tolkien" },
];
export default function BookPage() {
const book = books[0];
return (
<div>
<h1>{book.title}</h1>
<p>By {book.author}</p>
<p>Book {book.id} of 3</p>
</div>
);
}One address, one book
The check asks for book 1. The heading is Dune.
curl -s http://localhost:3000/books/1 | grep -o "<h1>Dune</h1>"The same file serves book 2
The check asks for book 2. The heading is Pride and Prejudice.
curl -s http://localhost:3000/books/2 | grep -o "<h1>Pride and Prejudice</h1>"Example
const books = ["Dune", "Pride and Prejudice", "The Hobbit"];
console.log("One file, three addresses:");
books.forEach((title, i) => console.log("/books/" + (i + 1) + " → " + title));Key points
- Dynamic route: one page file that serves many addresses
- app/books/[id]/page.tsx is a dynamic route. The [id] part changes with the address.
- /books/1 opens the page with id 1. /books/2 opens the same file with id 2.
- The page reads id from params. Params holds the changing part of the address.
- One file serves every book. No new file is needed for book 4.
In this example, the list holds the three book titles in order. One page file serves all three addresses. The number in the address picks the book: 1 is Dune, 2 is Pride and Prejudice, and 3 is The Hobbit. That number is the id, and the page reads it from params.
Note
params is a Promise in Next.js 15 and newer. The next lesson shows what that means.
Try it Yourself
Edit the code, then press Run.
Running is simulated · TypeScript Playground
Exercise
What does [id] mean in app/books/[id]/page.tsx?