Challenge - 5 Problems
Dynamic API Routes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this dynamic API route?
Consider a Next.js API route file named
pages/api/user/[id].js with the following code. What will be the JSON response when a GET request is made to /api/user/42?NextJS
export default function handler(req, res) { const { id } = req.query; res.status(200).json({ userId: id, message: `User ID is ${id}` }); }
Attempts:
2 left
💡 Hint
Remember that query parameters in Next.js API routes are always strings.
✗ Incorrect
The dynamic segment [id] is accessed via req.query.id as a string. The response JSON uses this string value for both userId and message.
📝 Syntax
intermediate2:00remaining
Which option correctly defines a catch-all dynamic API route?
You want to create a Next.js API route that catches all paths under
/api/posts/, including nested paths like /api/posts/2023/05. Which file name correctly implements this?Attempts:
2 left
💡 Hint
Catch-all routes use three dots inside square brackets.
✗ Incorrect
The correct syntax for catch-all dynamic routes in Next.js is [...param]. The file extension must be .js or .ts for API routes.
🔧 Debug
advanced2:00remaining
Why does this dynamic API route return 404 for /api/products/123?
Given the file
pages/api/product/[productId].js with this code, why does a request to /api/products/123 return 404?
export default function handler(req, res) {
const { productId } = req.query;
if (!productId) {
res.status(400).json({ error: 'Missing productId' });
return;
}
res.status(200).json({ id: productId });
}Attempts:
2 left
💡 Hint
Check the folder name in the file path carefully.
✗ Incorrect
If the folder name does not match the URL segment, Next.js cannot match the route, causing 404.
❓ state_output
advanced2:00remaining
What is the value of
slug in this catch-all API route?In a Next.js API route file named
pages/api/blog/[...slug].js, the handler is:
export default function handler(req, res) {
const { slug } = req.query;
res.status(200).json({ slug });
}
What is the JSON response when a request is made to /api/blog/2024/06/updates?Attempts:
2 left
💡 Hint
Catch-all routes provide an array of path segments.
✗ Incorrect
The catch-all dynamic route captures all path segments as an array in req.query.slug.
🧠 Conceptual
expert2:00remaining
Which statement about dynamic API routes in Next.js is TRUE?
Select the correct statement about dynamic API routes in Next.js.
Attempts:
2 left
💡 Hint
Think about how Next.js handles multiple path segments in dynamic routes.
✗ Incorrect
Catch-all routes use [...param] syntax and provide an array of segments in req.query.param.