Dynamic routes let your app show different pages based on the URL. This helps create pages for many items without making each page by hand.
0
0
Dynamic routes with [param] in NextJS
Introduction
You want to show a user profile page for each user using their ID in the URL.
You have a blog and want each post to have its own page based on the post's slug.
You need product pages that change depending on the product ID in the URL.
You want to build a details page for events where the event ID is part of the URL.
Syntax
NextJS
app/[param]/page.jsx
// or in pages directory
pages/[param].jsxThe folder or file name uses square brackets [param] to mark a dynamic part.
The param name is the variable you use to get the value from the URL.
Examples
This example shows a dynamic route where
id is the URL part you want to read.NextJS
app/[id]/page.jsx export default function Page({ params }) { return <p>ID is {params.id}</p>; }
Here,
slug is the dynamic part of the URL for a blog post.NextJS
pages/[slug].jsx export default function Post({ params }) { return <h1>Post: {params.slug}</h1>; }
Sample Program
This component shows a product page. The productId comes from the URL, so if you visit /product/123, it shows "Product ID: 123".
NextJS
app/product/[productId]/page.jsx export default function ProductPage({ params }) { return ( <main> <h1>Product Details</h1> <p>Product ID: {params.productId}</p> </main> ); }
OutputSuccess
Important Notes
Dynamic route parameters are always strings from the URL.
Use the params object in your component to access the dynamic parts.
Dynamic routes help keep your app organized and scalable.
Summary
Dynamic routes use square brackets [param] in file or folder names.
The params object gives you the dynamic value from the URL.
This lets you create many pages with one component by changing content based on the URL.