How to Create Dynamic Routes in Next.js Easily
In Next.js, create dynamic routes by adding square brackets around the file name inside the
pages folder, like [param].js. This lets you capture URL parts as variables accessible in your component via useRouter or getServerSideProps.Syntax
Dynamic routes in Next.js use file names with square brackets to capture URL segments as parameters.
pages/[param].js: Matches any URL like/somethingand capturessomethingasparam.pages/blog/[slug].js: Matches URLs like/blog/post-titleand capturespost-titleasslug.- Inside the component, use
useRouterfromnext/routerto accessrouter.query.param.
javascript
import { useRouter } from 'next/router'; export default function Page() { const router = useRouter(); const { param } = router.query; return <p>Dynamic route param: {param}</p>; }
Output
If you visit /hello, the page shows: Dynamic route param: hello
Example
This example shows a dynamic route that captures a username from the URL and displays it.
javascript
import { useRouter } from 'next/router'; export default function UserProfile() { const router = useRouter(); const { username } = router.query; if (!username) return <p>Loading...</p>; return <main> <h1>User Profile</h1> <p>Welcome, <strong>{username}</strong>!</p> </main>; }
Output
Visiting /user/john shows: User Profile Welcome, john!
Common Pitfalls
- Not using square brackets in the file name means the route is static, not dynamic.
- Accessing
router.querybefore it is ready can cause undefined values; check if the param exists. - Using dynamic routes without fallback handling in
getStaticPathscan cause build errors in static generation.
javascript
/* Wrong: static file name, no dynamic param */ // pages/user.js export default function User() { return <p>This is a static user page, no dynamic param.</p>; } /* Right: dynamic file name with param */ // pages/user/[username].js import { useRouter } from 'next/router'; export default function User() { const router = useRouter(); const { username } = router.query; return <p>User: {username}</p>; }
Quick Reference
- Use
[param].jsinpagesto create dynamic routes. - Access route parameters with
useRouteror data fetching methods. - For nested routes, use folders with dynamic file names like
pages/blog/[slug].js. - Check for parameter existence before using to avoid errors.
Key Takeaways
Create dynamic routes by naming files with square brackets like [param].js inside the pages folder.
Access dynamic parameters using useRouter's router.query object inside your component.
Always check if the dynamic parameter exists before using it to avoid undefined errors.
For static generation with dynamic routes, use getStaticPaths with fallback handling.
Nested dynamic routes are created by placing dynamic files inside folders, e.g., pages/blog/[slug].js.