Skip to content

Schema Validation

Validate all incoming API route data with Zod to prevent malformed or malicious input.

Install Zod

bash
npm install zod

Usage Pattern

javascript
// /app/api/user/route.js
import { NextResponse } from "next/server";
import { z } from "zod";

const schema = z.object({
  email: z.string().email(),
});

export async function POST(request) {
  const body = await request.json();
  const result = schema.safeParse(body);

  if (!result.success) {
    return NextResponse.json({ error: "Invalid input" }, { status: 400 });
  }

  const { email } = result.data;
  return NextResponse.json({ email });
}

Common Schema Types

javascript
import { z } from "zod";

// String with constraints
z.string().min(1).max(100)

// Email
z.string().email()

// URL
z.string().url()

// Number in range
z.number().min(0).max(100)

// Enum
z.enum(["subscription", "payment"])

// Optional field
z.string().optional()

// Object
z.object({
  name: z.string().min(1),
  email: z.string().email(),
  plan: z.enum(["starter", "pro"]).optional(),
})

Best Practice

Apply schema validation to every API route that accepts user input. Use safeParse (not parse) so you control the error response rather than letting Zod throw.

See Also