tezvyn:

Next.js Dynamic Routes: Pages on Demand

AI-drafted, machine-checkedSource: nextjs.orgintermediate

Think of dynamic routes as a page template. You create one file like `[slug].js` to generate unlimited unique pages for things like blog posts or products. The footgun is forgetting to handle non-existent slugs, which can crash your app.

WHY IT EXISTS Manually creating a new file for every single blog post, product, or user profile is unscalable. Dynamic routing was created to solve this by allowing a single file to act as a template for an entire category of pages, generating them based on data and the URL.

THE MENTAL MODEL Think of a dynamic route as a mail merge for web pages. You define a single layout template, like app/products/[id]/page.js. Next.js then uses this template to generate unique pages for /products/1, /products/2, and so on, by plugging the id from the URL into your component to fetch the correct data.

HOW IT WORKS Next.js uses a file-system convention. By wrapping a folder name in square brackets, like [slug], you tell Next.js that this part of the URL is a dynamic placeholder. In your page component, you receive this placeholder as a parameter. For example, in app/blog/[slug]/page.js, the component Page({ params }) will receive an object like { slug: 'my-first-post' } for the URL /blog/my-first-post. You then use params.slug to fetch and display the content for that specific post.

WHEN TO USE IT Use dynamic routes for any collection of items that share the same layout but have different content. Three classic examples: first, blog posts under /blog/[slug]; second, e-commerce product pages under /products/[productId]; third, user profiles under /users/[username].

WHEN NOT TO USE IT Avoid dynamic routes for unique, static pages like your homepage, about page, or contact page. For these, a simple file like app/about/page.js is clearer and more direct. If you only have a small, fixed set of sub-pages, creating individual files can also be less complex than setting up dynamic logic.

ONE CANONICAL EXAMPLE To create pages for individual blog posts, you would create a file at app/blog/[slug]/page.js. This single file can render an infinite number of routes. A request to /blog/hello-world would render the page.js component, passing it { params: { slug: 'hello-world' } }. The component then uses this slug to query a database or CMS for the post titled 'hello-world' and displays its content.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.