Performance: Catch-all API routes
Catch-all API routes impact server response time and routing efficiency, which affects how quickly the page can load dynamic data.
export default function handler(req, res) { const { slug } = req.query; // Use slug array directly to handle dynamic paths flexibly res.status(200).json({ path: slug }); }
export default function handler(req, res) { const { slug } = req.query; if (slug.length === 1) { // handle /api/post } else if (slug.length === 2) { // handle /api/post/comment } else { res.status(404).end(); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual slug length checks with multiple conditions | 0 (server-side) | 0 | 0 | [X] Bad |
| Uniform catch-all handler using slug array directly | 0 (server-side) | 0 | 0 | [OK] Good |
[...slug].js in Next.js do?[...name].js catch all nested paths under that route.req.query.name, here slug.[...slug].js.pages/api/[...params].js with this handler:export default function handler(req, res) {
res.json(req.query.params);
}/api/a/b/c?[...params] captures all path parts as an array in req.query.params.req.query.params as JSON, so the response is the array of parts.pages/api/[...slug].js but when you request /api (no extra path), you get an error. What is the likely cause?[...slug].js requires at least one path part; it does not match the base path alone./api with no extra parts, use optional catch-all [[...slug]].js./api/a/b/c it returns {"0": "a", "1": "b", "2": "c"}. Which handler code inside pages/api/[...parts].js achieves this?parts is an array of path parts. We want to create an object with keys as indices and values as parts.req.query.parts and assigns each part to the object with its index as key, then returns it as JSON.Pass the test and this pattern moves unknown