0
0
NextJSframework~15 mins

Dynamic route segments in NextJS - Deep Dive

Choose your learning style9 modes available
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.