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.

TypescriptNextData Fetching

Code

snippet
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: zod is a real dependency, resolved by the package manager.
  • The guard !parsed.success short-circuits the flow with an early return when 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

FAQ

Does this require external packages?
Yes — `zod`. Add it to your project before running the snippet.