0
0
NextjsHow-ToBeginner · 4 min read

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 /something and captures something as param.
  • pages/blog/[slug].js: Matches URLs like /blog/post-title and captures post-title as slug.
  • Inside the component, use useRouter from next/router to access router.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.query before it is ready can cause undefined values; check if the param exists.
  • Using dynamic routes without fallback handling in getStaticPaths can 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].js in pages to create dynamic routes.
  • Access route parameters with useRouter or 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.