Next.js API Route Handler
Create typed API route handlers in Next.js App Router with Zod validation, standard Response objects, error handling middleware, and OpenAPI-compatible.
Code
import { z } from 'zod';
const bodySchema = z.object({
name: z.string().min(1),
age: z.number().int().min(0).max(150),
});
export async function POST(request: Request) {
const json = await request.json();
const parsed = bodySchema.safeParse(json);
if (!parsed.success) {
return Response.json({ errors: parsed.error.issues }, { status: 400 });
}
const user = await db.user.create({ data: parsed.data });
return Response.json(user, { status: 201 });
}How the snippet works
The working surface is the function POST — everything else is wiring.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Reach for zod and what you get is z — that is the whole API contact area.
Caveats
- Plan for an install step:
zodis a real dependency, resolved by the package manager. - The guard
!parsed.successshort-circuits the flow with an earlyreturnwhen its condition holds.
Using it
Signature: export async function POST(request: Request)
The surface worth importing is POST; the helpers around it are private to the snippet.
Key statements
return Response.json({ errors: parsed.error.issues }, { status: 400 });
const user = await db.user.create({ data: parsed.data });
return Response.json(user, { status: 201 });
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does this require external packages?
- Yes — `zod`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.