Performance: Dynamic API routes
Dynamic API routes affect server response time and initial page load speed when fetching data from the server.
Jump into concepts and practice - no test required
export default function handler(req, res) { const { slug } = req.query; if (!slug || (Array.isArray(slug) && slug.length === 0)) { res.status(400).json({ error: 'Missing slug' }); return; } // Handle dynamic slug directly without multiple conditions res.status(200).json({ data: `Slug: ${Array.isArray(slug) ? slug.join('/') : slug}` }); }
export default function handler(req, res) { const { slug } = req.query; if (slug.length === 1) { // handle single slug res.status(200).json({ data: `Single slug: ${slug[0]}` }); } else if (slug.length === 2) { // handle two slugs res.status(200).json({ data: `Two slugs: ${slug[0]}, ${slug[1]}` }); } else { res.status(404).end(); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Complex conditional dynamic API route | N/A (server-side) | N/A | N/A | [X] Bad |
| Simplified uniform dynamic API route | N/A (server-side) | N/A | N/A | [OK] Good |
[id].js?[id].js indicate a dynamic segment in the URL path.id inside a Next.js API route handler in [id].js?req.query in API routes.id is done by req.query.id, not req.params or others.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}` });
}/api/user/42?/api/user/42 matches the dynamic route [userId].js, so userId is "42".userId from req.query and returns JSON with message including that value.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 });
}pid is missing, the code sends a 400 response but does not stop execution./api/order/[orderId]/item/[itemId].js. How should you structure the files and access both orderId and itemId inside the handler?orderId and itemId appear in req.query as separate keys.