How do you create dynamic API routes?
Use bracketed folder names, just like pages: app/api/users/[id]/route.ts handles /api/users/123. The value arrives in the second argument's params, which is a Promise you must await: const { id } = await ctx.params.
Variants
app/api/users/[id]/route.ts: one segment.app/api/files/[...path]/route.ts: catch-all,pathis a string array.app/api/docs/[[...slug]]/route.ts: optional catch-all.- Nested:
app/api/orgs/[orgId]/members/[memberId]/route.ts.
Typing
Use the generated RouteContext<'/api/users/[id]'> helper (from next typegen, also run by next dev and next build). It types params correctly, including arrays for catch-alls.
Static generation
With Cache Components, a GET handler for a dynamic route can export generateStaticParams to prerender known values, just like a page.
Validation
Params are user input. Validate format (UUID, number, slug) before using them in queries, and never build file paths from them without sanitizing.
Pages Router
pages/api/users/[id].ts and read req.query.id, which can be string | string[].
Code example
1// app/api/orgs/[orgId]/members/[memberId]/route.ts2import { z } from "zod";3import { db } from "@/lib/db";45const Params = z.object({ orgId: z.string().uuid(), memberId: z.string().uuid() });67export async function GET(_req: Request, ctx: RouteContext<"/api/orgs/[orgId]/members/[memberId]">) {8 const parsed = Params.safeParse(await ctx.params);9 if (!parsed.success) return Response.json({ error: "Invalid id" }, { status: 400 });1011 const { orgId, memberId } = parsed.data;12 const member = await db.member.findFirst({ where: { id: memberId, orgId } });1314 return member15 ? Response.json(member)16 : Response.json({ error: "Not found" }, { status: 404 });17}1819// app/api/files/[...path]/route.ts20// const { path } = await ctx.params; // ["images", "2026", "logo.png"]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.