0
0
NextJSframework~15 mins

Dynamic routes with [param] in NextJS - Deep Dive

Choose your learning style9 modes available
Overview - Dynamic routes with [param]
What is it?
Dynamic routes with [param] in Next.js let you create pages that change based on the URL part. Instead of making a page for every possible URL, you use a special file name with square brackets to catch that part. This way, one page can show different content depending on what the user types in the address bar. It makes websites flexible and easier to build.
Why it matters
Without dynamic routes, you would need to create a separate page for every possible URL, which is slow and hard to manage. Dynamic routes let your website respond to many URLs with just one page, saving time and making your site smarter. This means users get personalized content quickly, and developers can build faster.
Where it fits
Before learning dynamic routes, you should understand basic Next.js pages and file-based routing. After mastering dynamic routes, you can learn about nested dynamic routes, catch-all routes, and how to fetch data for these pages using Next.js data fetching methods.
Mental Model
Core Idea
Dynamic routes with [param] let one page template handle many URLs by capturing parts of the URL as variables.
Think of it like...
It's like a mail sorter who uses a label on each package to decide where it goes, instead of having a separate sorter for every address.
pages/
├── index.js       (static homepage)
├── about.js       (static about page)
└── [param].js     (dynamic page capturing 'param' from URL)

Example URL: /product123
Captured param: 'product123'

Flow:
User visits URL → Next.js finds [param].js → passes 'param' to page → page shows content for 'param'
Build-Up - 7 Steps
1
FoundationBasic file-based routing in Next.js
🤔
Concept: Next.js uses the files inside the pages folder to create routes automatically.
In Next.js, each file inside the pages folder becomes a route. For example, pages/index.js is the homepage at '/', and pages/about.js is at '/about'. You don't write route code manually; Next.js handles it for you.
Result
Visiting '/' shows the homepage, and '/about' shows the about page.
Understanding that file names map directly to URLs is key to grasping how dynamic routes extend this system.
2
FoundationStatic vs dynamic routes difference
🤔
Concept: Static routes have fixed URLs, while dynamic routes change based on URL parts captured as variables.
Static routes are files like about.js that always show the same page. Dynamic routes use square brackets in file names, like [param].js, to catch parts of the URL and use them inside the page.
Result
Static routes serve fixed pages; dynamic routes serve pages that change based on URL input.
Knowing this difference helps you decide when to use dynamic routes to avoid making many static pages.
3
IntermediateCreating a dynamic route with [param]
🤔Before reading on: Do you think the file name [param].js can capture any URL segment or only specific ones? Commit to your answer.
Concept: Using square brackets in a file name creates a dynamic route that captures any matching URL segment as a parameter.
Create a file named [param].js inside pages. When a user visits /something, Next.js runs [param].js and passes 'something' as a parameter called 'param'. Inside the page, you can access this param to show different content.
Result
Visiting /apple runs pages/[param].js with param='apple', so the page can show info about 'apple'.
Understanding that the file name itself defines the variable name is crucial for accessing URL parts inside your page.
4
IntermediateAccessing the param inside the page
🤔Before reading on: Do you think the param is available as a prop, a hook, or a global variable? Commit to your answer.
Concept: Next.js provides the dynamic param through the useRouter hook or as context in data fetching functions.
Inside [param].js, import useRouter from 'next/router'. Then call useRouter() to get router.query.param, which holds the URL part. You can use this value to fetch data or display content dynamically.
Result
The page shows content based on the param value from the URL, like 'apple' or 'banana'.
Knowing how to get the param inside the page lets you build dynamic, personalized pages.
5
IntermediatePre-rendering dynamic routes with getStaticPaths
🤔Before reading on: Do you think Next.js can pre-build all dynamic pages automatically or do you need to tell it which ones? Commit to your answer.
Concept: To pre-build dynamic pages at build time, you must specify which params to generate using getStaticPaths.
In [param].js, export an async function getStaticPaths that returns an array of params to pre-render. Next.js uses this to create static pages for those params. If a param is not listed, the page can fallback or show 404.
Result
Next.js builds static pages for specified params, improving performance and SEO.
Understanding getStaticPaths is key to controlling which dynamic pages are ready before users visit.
6
AdvancedCatch-all routes with [[...param]]
🤔Before reading on: Do you think catch-all routes capture one or multiple URL parts? Commit to your answer.
Concept: Catch-all routes capture multiple URL segments as an array, allowing flexible nested paths.
Create a file named [[...param]].js to catch zero or more URL parts. For example, /a/b/c passes ['a','b','c'] as param. This is useful for deeply nested dynamic routes.
Result
The page can handle URLs with many segments dynamically, like /docs/2024/nextjs/tutorial.
Knowing catch-all routes lets you build complex URL structures with one page.
7
ExpertDynamic routes and server-side rendering tradeoffs
🤔Before reading on: Do you think dynamic routes always use static generation or can they also use server-side rendering? Commit to your answer.
Concept: Dynamic routes can use static generation, server-side rendering, or client-side rendering, each with tradeoffs in speed and freshness.
You can use getStaticProps with getStaticPaths for static pages, or getServerSideProps for server-rendered pages that update on each request. Choosing depends on data freshness needs and performance.
Result
You balance build time, runtime speed, and data freshness by picking the right rendering method for dynamic routes.
Understanding rendering tradeoffs helps build scalable, fast, and up-to-date dynamic pages.
Under the Hood
Next.js uses the file system to map URLs to files. When it sees a file named [param].js, it treats the part of the URL matching that position as a variable. At runtime or build time, Next.js extracts this variable and passes it to the page component via router.query or data fetching functions. For static generation, Next.js uses getStaticPaths to know which params to pre-build. For server-side rendering, it runs the page code on each request with the param available. This system leverages Node.js routing and React rendering under the hood.
Why designed this way?
Next.js was designed to simplify routing by using the file system, a familiar concept for developers. Dynamic routes with [param] were introduced to avoid manual route definitions and to handle many URLs efficiently. Alternatives like manual route config were more complex and error-prone. This design balances simplicity, flexibility, and performance, making it easy to build scalable apps.
URL: /product/123

┌─────────────┐
│  Next.js    │
│  Router     │
└─────┬───────┘
      │ matches /product/[param]
      ▼
┌─────────────┐
│ [param].js  │
│ receives   │
│ param='123'│
└─────┬───────┘
      │
      ▼
┌─────────────┐
│ React Page  │
│ renders UI  │
│ with param  │
└─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does [param].js only match URLs with exactly one segment? Commit to yes or no.
Common Belief:People often think [param].js matches only one URL segment and cannot handle nested paths.
Tap to reveal reality
Reality:[param].js matches exactly one segment, but nested paths require catch-all routes like [[...param]].js.
Why it matters:Misunderstanding this leads to broken routes or 404 errors when trying to handle nested URLs with simple dynamic routes.
Quick: Do you think getStaticPaths runs on every user request? Commit to yes or no.
Common Belief:Some believe getStaticPaths runs on every request to generate pages dynamically.
Tap to reveal reality
Reality:getStaticPaths runs only at build time to pre-generate pages, not on every request.
Why it matters:Confusing this causes wrong expectations about data freshness and build times.
Quick: Is the param value always a string? Commit to yes or no.
Common Belief:Many assume the param is always a string value.
Tap to reveal reality
Reality:For catch-all routes, the param is an array of strings representing multiple URL parts.
Why it matters:Treating param as a string when it's an array causes bugs and crashes in the app.
Quick: Does dynamic routing mean slower page loads? Commit to yes or no.
Common Belief:Some think dynamic routes always slow down page loading because they are dynamic.
Tap to reveal reality
Reality:Dynamic routes can be statically generated for fast loads or server-rendered for fresh data; performance depends on rendering choice.
Why it matters:Assuming dynamic routes are slow may lead developers to avoid them unnecessarily, limiting app flexibility.
Expert Zone
1
Dynamic route parameter names must be unique within the same folder to avoid conflicts, which can cause subtle routing bugs.
2
Using fallback: 'blocking' in getStaticPaths allows on-demand generation of pages not pre-built, balancing build time and user experience.
3
Catch-all routes can overlap with static routes, so route priority rules in Next.js affect which page renders, a detail often overlooked.
When NOT to use
Avoid dynamic routes when URLs are fixed and few; static routes are simpler and faster. For very complex nested routes, consider API routes or middleware for better control.
Production Patterns
In production, dynamic routes are combined with getStaticPaths and incremental static regeneration to pre-build popular pages and update them over time. Catch-all routes handle nested content like blogs or docs. Server-side rendering is used for user-specific pages requiring fresh data.
Connections
REST API endpoints
Dynamic routes in Next.js mirror REST API path parameters that capture variable parts of URLs.
Understanding dynamic routes helps grasp how REST APIs use path variables to serve different resources with one endpoint.
Regular expressions
Dynamic route matching is similar to capturing groups in regular expressions that extract parts of strings.
Knowing how regex groups work clarifies how Next.js extracts params from URLs in dynamic routes.
Postal addressing system
Dynamic routes function like postal addresses where parts of the address specify location details dynamically.
Recognizing this connection shows how hierarchical information can be encoded and decoded efficiently in different systems.
Common Pitfalls
#1Trying to access the param directly as a prop without using useRouter or data fetching context.
Wrong approach:function Page({ param }) { return
{param}
; } export default Page;
Correct approach:import { useRouter } from 'next/router'; function Page() { const router = useRouter(); const { param } = router.query; return
{param}
; } export default Page;
Root cause:Misunderstanding how Next.js passes dynamic route params; they are not direct props but accessed via router or data fetching.
#2Not exporting getStaticPaths when using getStaticProps in a dynamic route, causing build errors.
Wrong approach:export async function getStaticProps(context) { // fetch data return { props: {} }; } // missing getStaticPaths
Correct approach:export async function getStaticPaths() { return { paths: [], fallback: true }; } export async function getStaticProps(context) { // fetch data return { props: {} }; }
Root cause:For static generation of dynamic routes, Next.js requires getStaticPaths to know which pages to build.
#3Using [param].js to try to catch multiple URL segments separated by slashes.
Wrong approach:pages/[param].js handles /a/b/c expecting param='a/b/c', but it only captures 'a'.
Correct approach:Use pages/[[...param]].js to capture multiple segments as an array: ['a','b','c'].
Root cause:Confusing single dynamic segments with catch-all routes that handle multiple segments.
Key Takeaways
Dynamic routes with [param] let one page handle many URLs by capturing parts of the URL as variables.
Next.js uses file names with square brackets to define dynamic segments, making routing simple and automatic.
You access dynamic params inside pages using the useRouter hook or data fetching functions like getStaticProps.
Pre-building dynamic pages requires getStaticPaths to tell Next.js which URLs to generate at build time.
Catch-all routes [[...param]] capture multiple URL parts, enabling flexible nested routing structures.