Next.js Course
Next.js
/
Intermediate

Dynamic Routes

Definition

Routes that are not fixed strings, but act as variables to capture data from the URL (like an ID or a slug). Created by wrapping a folder name in square brackets: `[param]`.

Explain Like I'm New

If you have 10,000 blog posts, you can't create 10,000 folders. You create ONE folder called `[slug]`. If the user visits `/blog/my-trip-to-japan`, Next.js routes it to the `[slug]` folder and passes 'my-trip-to-japan' into your component as a variable.

Real World Example

An e-commerce site where `/products/123` and `/products/456` both use the exact same React component, but fetch different product data based on the ID.

Common Use Cases

  • •Blog posts
  • •User profiles
  • •E-commerce product pages

Interactive Example

/* 
  File Path: app/users/[id]/page.tsx
  URL Visited: mywebsite.com/users/99
*/

// The component receives the 'params' object automatically!
export default function UserProfile({ params }: { params: { id: string } }) {
  
  // params.id will equal "99"
  const userId = params.id;
  
  return (
    <div>
      <h1>User Profile for ID: {userId}</h1>
      {/* You would usually fetch data from a DB using this ID here */}
    </div>
  )
}

Interview Questions

basic

  • How do you define a dynamic route folder that captures a user's ID?

intermediate

  • How do you access the dynamic variable inside your `page.tsx` component?

Flash Cards

Question

How to define?

Click to reveal answer
Answer

Name the folder with square brackets: `[id]` or `[userId]`.

Question

How to access?

Click to reveal answer
Answer

Next.js automatically passes a `params` prop to your page component. You would access it via `params.id`.