Bird
Raised Fist0
NextJSframework~15 mins

Dynamic route segments in NextJS - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Dynamic route segments
What is it?
Dynamic route segments in Next.js let you create pages that change based on the URL parts. Instead of making a page for every possible URL, you use placeholders that match different values. This helps build websites where content changes, like user profiles or product pages. The page adapts automatically to the URL segment it receives.
Why it matters
Without dynamic route segments, you would need to create a separate page for every possible URL, which is impossible for large or changing sites. This would make websites slow to build and hard to maintain. Dynamic segments let developers build flexible, scalable apps that respond to user input or data without extra code for each case.
Where it fits
Before learning dynamic route segments, you should understand basic Next.js routing and file-based pages. After mastering dynamic segments, you can explore nested dynamic routes, catch-all routes, and API routes to build complex apps.
Mental Model
Core Idea
Dynamic route segments are placeholders in URL paths that let one page handle many different URLs by capturing parts of the path as variables.
Think of it like...
It's like a mail sorting system where instead of having a separate mailbox for every person, you have one mailbox with a label slot that changes depending on the recipient's name written on the letter.
pages/
├── [user]
│   └── index.js
└── product
    └── [id].js

URL examples:
- /alice → matches [user]/index.js with user='alice'
- /product/123 → matches product/[id].js with id='123'
Build-Up - 7 Steps
1
FoundationBasic file-based routing in Next.js
🤔
Concept: Next.js uses files in the pages folder to create routes automatically.
Each file inside the pages directory becomes a route. For example, pages/index.js is the homepage at '/'. pages/about.js is '/about'. This is called file-based routing.
Result
Visiting '/about' loads the About page component from pages/about.js.
Understanding file-based routing is essential because dynamic segments build on this system by adding flexibility to the file names.
2
FoundationStatic vs dynamic routes explained
🤔
Concept: Static routes have fixed URLs, dynamic routes use placeholders to match many URLs.
Static route example: pages/contact.js → '/contact'. Dynamic route example: pages/[username].js matches '/alice', '/bob', etc. The part in brackets is a dynamic segment.
Result
Dynamic routes let one file handle many URLs by capturing the dynamic part as a variable.
Knowing the difference helps you decide when to use dynamic segments to avoid creating many static pages.
3
IntermediateCreating a single dynamic segment route
🤔Before reading on: do you think the dynamic segment value is passed as a prop or accessed differently? Commit to your answer.
Concept: Dynamic segments are defined by square brackets in filenames and their values are passed as props to the page component.
Create a file pages/[slug].js. Inside, use the useRouter hook or getStaticProps to access the slug value. For example: import { useRouter } from 'next/router'; export default function Page() { const router = useRouter(); const { slug } = router.query; return

Slug is {slug}

; } Visiting '/hello' shows 'Slug is hello'.
Result
The page dynamically shows content based on the URL segment captured as 'slug'.
Understanding how Next.js passes dynamic segment values lets you build pages that react to URL changes.
4
IntermediateMultiple dynamic segments in nested folders
🤔Before reading on: do you think nested dynamic segments require special syntax or just nested folders? Commit to your answer.
Concept: You can nest dynamic segments by creating folders and files with bracket names inside pages.
Example structure: pages/ └── blog/ └── [category]/ └── [post].js Visiting '/blog/tech/nextjs' matches blog/[category]/[post].js with category='tech' and post='nextjs'. Access both via router.query.
Result
You can capture multiple parts of the URL as separate variables for complex routing.
Knowing nested dynamic segments lets you build detailed URL structures that reflect your content hierarchy.
5
IntermediateCatch-all routes for flexible matching
🤔Before reading on: do you think catch-all routes capture one or multiple URL segments? Commit to your answer.
Concept: Catch-all routes use triple dots inside brackets to capture multiple segments as an array.
Create pages/[...params].js. Visiting '/a/b/c' sets params = ['a', 'b', 'c']. You can use this to handle any depth of URL paths dynamically.
Result
One page can handle many URL shapes, useful for file explorers or nested content.
Catch-all routes provide maximum flexibility for dynamic routing beyond fixed segment counts.
6
AdvancedStatic generation with dynamic segments
🤔Before reading on: do you think static generation works automatically with dynamic routes or needs extra code? Commit to your answer.
Concept: To statically generate dynamic pages, you must tell Next.js which paths to build at build time using getStaticPaths.
In pages/[id].js, export async function getStaticPaths() { return { paths: [{ params: { id: '1' } }, { params: { id: '2' } }], fallback: false }; } and getStaticProps to fetch data for each id. This pre-builds pages for those ids.
Result
Your app serves fast static pages for dynamic routes without server delays.
Knowing how to combine dynamic routes with static generation improves performance and SEO.
7
ExpertDynamic segments with middleware and rewrites
🤔Before reading on: do you think middleware can change dynamic route behavior or only static routes? Commit to your answer.
Concept: Next.js middleware can intercept requests and modify dynamic route handling, and rewrites can map URLs to different dynamic routes.
Middleware runs before rendering and can redirect or rewrite URLs based on dynamic segments. For example, you can redirect '/old/[slug]' to '/new/[slug]' or add authentication checks dynamically.
Result
You gain fine control over routing logic beyond file structure, enabling advanced use cases.
Understanding middleware and rewrites with dynamic segments unlocks powerful routing customizations in production apps.
Under the Hood
Next.js routing uses the filesystem to map URLs to React components. When a URL matches a dynamic segment, Next.js extracts the segment value from the path and passes it as a parameter to the page component. During build time, static generation uses getStaticPaths to know which dynamic paths to pre-render. At runtime, client-side navigation uses these parameters to fetch or display content without full reloads.
Why designed this way?
This design leverages the simplicity of file-based routing while adding flexibility through dynamic segments. It avoids complex manual route definitions and keeps routing declarative. Alternatives like manual route configs were more error-prone and less intuitive. The filesystem approach fits well with React's component model and Next.js's hybrid rendering.
┌───────────────┐
│ URL Request   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Match Route   │
│ (static or    │
│ dynamic)      │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Extract Params│
│ from URL      │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Render Page   │
│ with params   │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think dynamic route segments always require server-side rendering? Commit to yes or no.
Common Belief:Dynamic routes must be rendered on the server every time because the content changes.
Tap to reveal reality
Reality:Dynamic routes can be statically generated at build time using getStaticPaths and getStaticProps, serving fast static pages.
Why it matters:Believing dynamic routes always need server rendering can lead to slower apps and missed performance optimizations.
Quick: Do you think catch-all routes capture only one URL segment? Commit to yes or no.
Common Belief:Catch-all routes only capture a single dynamic segment like normal dynamic routes.
Tap to reveal reality
Reality:Catch-all routes capture multiple segments as an array, allowing flexible matching of deep URL paths.
Why it matters:Misunderstanding catch-all routes limits their use and causes incorrect routing setups.
Quick: Do you think dynamic segment names must match query parameter names exactly? Commit to yes or no.
Common Belief:The name inside brackets must match the query parameter name used in the code exactly.
Tap to reveal reality
Reality:Yes, the bracket name defines the key in router.query or params, so they must match to access the value correctly.
Why it matters:Incorrect naming causes undefined values and bugs in accessing dynamic parameters.
Quick: Do you think middleware cannot modify dynamic route parameters? Commit to yes or no.
Common Belief:Middleware only runs for static routes and cannot change dynamic route behavior.
Tap to reveal reality
Reality:Middleware runs for all routes and can rewrite or redirect dynamic routes based on parameters.
Why it matters:Ignoring middleware's power limits routing flexibility and security options.
Expert Zone
1
Dynamic segments can be combined with optional catch-all segments ([...slug] vs [[...slug]]) to handle missing parameters gracefully.
2
Using getStaticPaths with fallback: 'blocking' allows incremental static generation for dynamic routes not pre-built at deploy time.
3
Middleware can rewrite URLs before routing, enabling complex authentication or localization logic tied to dynamic segments.
When NOT to use
Avoid dynamic route segments when URLs are fixed and few in number; static routes are simpler and faster. For very complex routing logic, consider using a custom server or API routes. Also, if you need query parameters instead of path segments, dynamic routes are not the right tool.
Production Patterns
In production, dynamic segments are used for user profiles, blog posts, product pages, and nested categories. Teams combine getStaticPaths with incremental static regeneration for performance. Middleware enforces auth on dynamic routes. Catch-all routes power file explorers or multi-level navigation.
Connections
REST API endpoints
Dynamic route segments in Next.js correspond to variable path parameters in REST APIs.
Understanding dynamic routes helps grasp how REST APIs use path variables to identify resources.
Regular expressions
Dynamic segments act like simple pattern matchers capturing parts of strings similar to regex groups.
Knowing regex groups clarifies how dynamic segments extract variable parts from URLs.
Human language grammar
Dynamic segments are like placeholders in sentence templates that get filled with different words to create meaning.
This connection shows how flexible structures can generate many variations from one pattern.
Common Pitfalls
#1Using the wrong bracket syntax for dynamic segments.
Wrong approach:pages/[slug/index.js (missing closing bracket)
Correct approach:pages/[slug]/index.js
Root cause:Misunderstanding the required syntax for dynamic segment folder or file names.
#2Not exporting getStaticPaths for static generation of dynamic routes.
Wrong approach:export async function getStaticProps() { /* fetch data */ } // no getStaticPaths
Correct approach:export async function getStaticPaths() { return { paths: [], fallback: false }; }
Root cause:Confusing getStaticProps with getStaticPaths and missing the required paths list.
#3Accessing dynamic segment parameters before router is ready.
Wrong approach:const { slug } = router.query; // used immediately without checking router.isReady
Correct approach:if (!router.isReady) return null; const { slug } = router.query;
Root cause:Not accounting for client-side router loading delay causing undefined params.
Key Takeaways
Dynamic route segments let one page handle many URLs by capturing parts of the path as variables.
They use square brackets in filenames to define placeholders that Next.js matches to URL parts.
Nested and catch-all dynamic segments allow flexible and deep URL structures.
Static generation of dynamic routes requires getStaticPaths to specify which pages to build.
Middleware and rewrites extend dynamic routing with powerful control over requests.

Practice

(1/5)
1. In Next.js, what does a file named [id].js inside the pages folder represent?
easy
A. A configuration file for setting environment variables
B. A static page that only matches the URL /id
C. A special API route for handling requests with an id parameter
D. A dynamic route segment that matches any value in the URL at that position

Solution

  1. Step 1: Understand Next.js routing conventions

    Files inside the pages folder define routes. Square brackets [] indicate dynamic segments.
  2. Step 2: Interpret [id].js meaning

    The file [id].js matches any URL segment in that position and passes it as a parameter named id.
  3. Final Answer:

    A dynamic route segment that matches any value in the URL at that position -> Option D
  4. Quick Check:

    Dynamic route = [segment] [OK]
Hint: Square brackets mean dynamic URL part in Next.js routes [OK]
Common Mistakes:
  • Thinking [id].js is a static page
  • Confusing dynamic routes with API routes
  • Assuming it matches only the literal 'id'
2. Which of the following is the correct syntax to define a dynamic route segment for a Next.js page that captures a username?
easy
A. pages/:username.js
B. pages/username.js
C. pages/[username].js
D. pages/{username}.js

Solution

  1. Step 1: Recall Next.js dynamic route syntax

    Dynamic segments use square brackets around the parameter name inside the pages folder.
  2. Step 2: Match syntax for username parameter

    The correct syntax is [username].js to capture the username dynamically.
  3. Final Answer:

    pages/[username].js -> Option C
  4. Quick Check:

    Dynamic segment uses [param] syntax [OK]
Hint: Use square brackets for dynamic route names [OK]
Common Mistakes:
  • Using colon or curly braces instead of square brackets
  • Naming the file without brackets for dynamic routes
  • Confusing dynamic routes with static filenames
3. Given the file structure:
pages/blog/[slug].js
and the URL /blog/hello-world, what will be the value of the slug parameter inside the page component?
medium
A. "hello-world"
B. "blog"
C. "[slug]"
D. undefined

Solution

  1. Step 1: Identify dynamic segment from file name

    The file [slug].js captures the URL segment after /blog/ as slug.
  2. Step 2: Match URL segment to parameter

    For URL /blog/hello-world, the segment hello-world is assigned to slug.
  3. Final Answer:

    "hello-world" -> Option A
  4. Quick Check:

    URL segment after folder = slug value [OK]
Hint: Dynamic segment captures URL part matching filename [OK]
Common Mistakes:
  • Using folder name as parameter value
  • Assuming parameter is the literal filename
  • Expecting undefined if parameter not explicitly passed
4. Consider this Next.js dynamic route file: pages/product/[id].js. Which of the following code snippets correctly accesses the id parameter inside the component?
medium
A. const router = useRouter(); const { id } = router.query;
B. const { id } = props.params;
C. const id = useParams().id;
D. const id = getIdFromUrl();

Solution

  1. Step 1: Recall how to access route params in Next.js pages

    Next.js uses the useRouter hook from next/router to access query parameters.
  2. Step 2: Identify correct syntax for extracting id

    The correct way is const router = useRouter(); const { id } = router.query;.
  3. Final Answer:

    const router = useRouter(); const { id } = router.query; -> Option A
  4. Quick Check:

    useRouter().query gives dynamic params [OK]
Hint: Use useRouter().query to get dynamic route params [OK]
Common Mistakes:
  • Using props.params which is not standard in Next.js pages
  • Using useParams() which is from React Router, not Next.js
  • Calling undefined functions like getIdFromUrl()
5. You want to create a nested dynamic route in Next.js to handle URLs like /dashboard/user/123 where 123 is a user ID. Which file structure correctly implements this?
hard
A. pages/dashboard/[user]/[id].js
B. pages/dashboard/user/[id].js
C. pages/dashboard/[id].js
D. pages/[dashboard]/user/[id].js

Solution

  1. Step 1: Analyze the URL structure

    The URL /dashboard/user/123 has three segments: dashboard, user, and a dynamic id.
  2. Step 2: Match file structure to URL segments

    Static segments dashboard and user are folders, and [id].js captures the dynamic user ID.
  3. Step 3: Verify options

    pages/dashboard/user/[id].js matches the folder structure exactly. Options B and D incorrectly treat static parts as dynamic. pages/dashboard/[id].js misses the user folder.
  4. Final Answer:

    pages/dashboard/user/[id].js -> Option B
  5. Quick Check:

    Static folders + [id].js for dynamic segment [OK]
Hint: Match URL parts to folders; dynamic parts use [param].js [OK]
Common Mistakes:
  • Making static parts dynamic segments
  • Omitting intermediate folders for static URL parts
  • Confusing order of folders and dynamic files