What if one file could handle thousands of API endpoints automatically?
Why Dynamic API routes in NextJS? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a web app where you need a separate API file for every user or product ID, like /api/user1, /api/user2, and so on.
You have to create hundreds of files manually to handle each case.
This manual approach is slow and messy.
It's hard to maintain, easy to make mistakes, and impossible to scale when new IDs appear.
Every time you add a new user or product, you must write new code files.
Dynamic API routes let you write one flexible route file that handles many different URLs by capturing parts of the path as variables.
This means you write less code and your API automatically works for any ID without extra files.
pages/api/user1.js pages/api/user2.js // one file per user ID
pages/api/[userId].js // one file handles all user IDs dynamically
You can build scalable APIs that respond to many different inputs with just a few smart files.
An online store where the API fetches product details based on the product ID in the URL, without needing a file for each product.
Manual API files for each ID are slow and unmanageable.
Dynamic API routes capture URL parts as variables automatically.
This makes APIs scalable, clean, and easy to maintain.
Practice
[id].js?Solution
Step 1: Understand file naming in Next.js API routes
Square brackets in filenames like[id].jsindicate a dynamic segment in the URL path.Step 2: Recognize the effect on routing
This allows the API route to capture the value in that part of the URL and use it inside the handler.Final Answer:
To create dynamic API routes that capture parts of the URL -> Option AQuick Check:
Dynamic routes use brackets = D [OK]
- Thinking brackets mark static routes
- Confusing with dynamic imports
- Assuming brackets define middleware
id inside a Next.js API route handler in [id].js?Solution
Step 1: Recall how Next.js passes dynamic route params
Next.js provides dynamic route parameters insidereq.queryin API routes.Step 2: Identify the correct syntax
Accessingidis done byreq.query.id, notreq.paramsor others.Final Answer:
const id = req.query.id; -> Option CQuick Check:
Dynamic params in API routes = req.query [OK]
- Using req.params instead of req.query
- Trying to get params from req.body
- Using incorrect property like req.route
pages/api/user/[userId].js with this handler:export default function handler(req, res) {
const { userId } = req.query;
res.status(200).json({ message: `User ID is ${userId}` });
}What will be the JSON response when a client requests
/api/user/42?Solution
Step 1: Extract dynamic parameter from URL
The URL/api/user/42matches the dynamic route[userId].js, souserIdis "42".Step 2: Check the handler response
The handler readsuserIdfromreq.queryand returns JSON with message including that value.Final Answer:
{"message":"User ID is 42"} -> Option DQuick Check:
Dynamic param value used in response = A [OK]
- Expecting literal string 'userId' instead of value
- Assuming undefined if param missing
- Thinking route returns 404 for dynamic routes
pages/api/product/[pid].js with the handler:export default function handler(req, res) {
const pid = req.query.pid;
if (!pid) {
res.status(400).json({ error: "Product ID missing" });
}
res.status(200).json({ productId: pid });
}What is the bug in this code?
Solution
Step 1: Analyze the conditional response
Ifpidis missing, the code sends a 400 response but does not stop execution.Step 2: Understand HTTP response behavior
Without a return after sending 400, the code continues and tries to send a 200 response, causing an error.Final Answer:
It does not return after sending 400 response, causing headers to be sent twice -> Option BQuick Check:
Return after error response to avoid double send [OK]
- Ignoring missing return after res.status(400).json()
- Confusing req.query with req.params
- Thinking res.send is required over res.json
/api/order/[orderId]/item/[itemId].js. How should you structure the files and access both orderId and itemId inside the handler?Solution
Step 1: Understand nested dynamic routes in Next.js
Next.js supports nested folders with dynamic segments using square brackets for each segment.Step 2: Access multiple dynamic params in handler
BothorderIdanditemIdappear inreq.queryas separate keys.Final Answer:
Create nested folders: pages/api/order/[orderId]/item/[itemId].js and access via req.query.orderId and req.query.itemId -> Option AQuick Check:
Nested folders with brackets = multiple params in req.query [OK]
- Trying to parse multiple params in one filename
- Using query string instead of dynamic routes
- Assuming req.query returns array for multiple params
