Challenge - 5 Problems
Catch-all 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 catch-all API route?
Consider a Next.js API route file named
pages/api/[...slug].js with the following code. What will be the JSON response when a GET request is made to /api/a/b/c?NextJS
export default function handler(req, res) { const { slug } = req.query; res.status(200).json({ path: slug }); }
Attempts:
2 left
💡 Hint
Remember that catch-all routes capture all parts of the URL as an array in the query.
✗ Incorrect
In Next.js, catch-all API routes like [...slug].js capture the URL parts after /api/ as an array in req.query.slug. So /api/a/b/c sets slug to ["a", "b", "c"].
📝 Syntax
intermediate1:30remaining
Which catch-all API route filename is valid in Next.js?
Which of the following filenames correctly defines a catch-all API route in Next.js?
Attempts:
2 left
💡 Hint
Catch-all routes use three dots inside square brackets before the name.
✗ Incorrect
The correct syntax for catch-all routes is [...name].js. Option C matches this. Option C has dots after the name which is invalid. Option C is a single dynamic route, not catch-all. Option C uses .jsx which is not valid for API routes.
🔧 Debug
advanced2:30remaining
Why does this catch-all API route return 404 for /api?
Given a catch-all API route file
pages/api/[...params].js with this code:
export default function handler(req, res) {
const { params } = req.query;
res.status(200).json({ params });
}
Why does a GET request to /api return 404 Not Found?Attempts:
2 left
💡 Hint
Think about how catch-all routes match URLs with zero or more segments.
✗ Incorrect
Catch-all routes like [...params].js match URLs with one or more segments after /api/. The base /api path has zero segments, so it does not match this route and returns 404.
❓ state_output
advanced2:00remaining
What is the value of req.query.slug for /api/foo?
In a Next.js API route file named
pages/api/[...slug].js, what is the value of req.query.slug when a GET request is made to /api/foo?NextJS
export default function handler(req, res) { res.status(200).json({ slug: req.query.slug }); }
Attempts:
2 left
💡 Hint
Catch-all routes always return an array for the matched segments.
✗ Incorrect
For catch-all routes, even a single segment like /api/foo is captured as an array with one element: ["foo"].
🧠 Conceptual
expert3:00remaining
How to handle both /api and /api/* with catch-all routes?
You want to create a Next.js API that handles requests to
/api and all sub-paths like /api/a/b using catch-all routes. Which setup correctly handles both cases?Attempts:
2 left
💡 Hint
Next.js supports optional catch-all routes with double brackets.
✗ Incorrect
The optional catch-all route [[...slug]].js matches /api (with slug undefined) and any sub-paths like /api/a/b (slug is array). This single file handles both cases.