All Posts

December 5, 2024 · 1 min read

Type-Safe API Routes in Next.js App Router

TypeScriptNext.jsZod

The problem with untyped handlers

Route handlers receive a raw Request. Without validation, req.json() returns unknown and you end up with type assertions scattered everywhere. One bad deploy later and you discover the client sent a string where you expected a number.

Zod at the boundary

Parse the request body with a Zod schema at the top of every POST handler. If parse fails, return a 400 with the flattened error immediately. Everything below that point is fully typed — no assertions needed.

Typed response helpers

A small typed wrapper around NextResponse.json() that accepts a generic enforces the response shape at the call site. When the schema changes, TypeScript tells you every handler that needs updating — no grep required.