Dynamic route segments let you create pages that change based on the URL. This helps show different content without making many separate pages.
0
0
Dynamic route segments in NextJS
Introduction
Showing user profiles where each user has a unique ID in the URL.
Displaying blog posts where the post ID or slug changes per article.
Creating product pages where each product has its own page based on its ID.
Building category pages where the category name is part of the URL.
Handling any page where part of the URL needs to be flexible and dynamic.
Syntax
NextJS
app/[segment]/page.js
Use square brackets [] around the folder or file name to mark it as dynamic.
The name inside brackets becomes a variable you can use in your code.
Examples
This creates a dynamic route where
userId changes based on the URL, like /123 or /alice.NextJS
app/[userId]/page.js
This sets up dynamic blog post pages where
slug is the post identifier in the URL.NextJS
app/blog/[slug]/page.js
Each product page URL uses a dynamic
productId segment.NextJS
app/products/[productId]/page.js
Sample Program
This component shows a user profile page. It reads the dynamic userId from the URL and displays it on the page.
For example, visiting /123 will show "User ID: 123".
NextJS
'use client'; import { useParams } from 'next/navigation'; export default function UserPage() { const params = useParams(); return ( <main> <h1>User Profile</h1> <p>User ID: {params.userId}</p> </main> ); } // File path: app/[userId]/page.js
OutputSuccess
Important Notes
Dynamic segments must be inside the app folder in Next.js 13+ App Router.
You can access the dynamic segment value using the useParams() hook.
Dynamic routes help keep your app organized and avoid creating many similar files.
Summary
Dynamic route segments let URLs change parts to show different content.
Use square brackets [] in folder or file names to create dynamic routes.
Access the dynamic part in your component with useParams().