In web development, we often need to display content that varies based on a specific identifier in the URL. Think of a blog where each post has a unique slug, or an e-commerce site where each product has an ID. Next.js makes handling these dynamic URLs incredibly straightforward with its dynamic routing feature.
The core concept behind dynamic routes in Next.js is the use of square brackets [] in your file and folder names within the pages directory. These brackets indicate that the enclosed part of the URL is a parameter that can change.
For example, if you want to create a page that displays a user's profile based on their username, you would create a file named pages/users/[username].js. The [username] part signifies a dynamic segment. When a user navigates to /users/alice, Next.js will match this route, and the value alice will be accessible within your page component.
import { useRouter } from 'next/router'
function UserProfile() {
const router = useRouter()
const { username } = router.query
return (
<div>
<h1>User Profile: {username}</h1>
{/* Display user-specific content here */}
</div>
)
}
export default UserProfileThe useRouter hook from next/router is your gateway to accessing these dynamic route parameters. The router.query object will contain key-value pairs where the keys are the names of your dynamic segments (e.g., username) and the values are the corresponding parts of the URL.
You can also have multiple dynamic segments within a single route. For instance, a route like pages/posts/[category]/[slug].js would allow URLs such as /posts/technology/nextjs-dynamic-routes. The router.query object would then contain { category: 'technology', slug: 'nextjs-dynamic-routes' }.
graph TD
A[pages/users/[username].js] --> B{URL: /users/alice}
B --> C[router.query.username = 'alice']
A --> D{URL: /users/bob}
D --> E[router.query.username = 'bob']
For situations where you need to match a variable number of segments (like an API path), Next.js offers catch-all routes. These are defined using double square brackets [[...slug]]. A file named pages/docs/[...slug].js would match any path starting with /docs/, such as /docs/getting-started, /docs/api/authentication, or /docs/guides/advanced-features.