Validating API Input in Node.js With Zod

Never trust input — validate it at the edge of your system

Most API bugs and many security issues start with unexpected input. Validate everything that crosses into your system: request bodies, query strings, params, headers, webhook payloads — and AI model outputs.

Defining a Schema

import { z } from 'zod';

export const CreateTicket = z.object({
  summary: z.string().trim().min(5).max(200),
  priority: z.enum(['low', 'medium', 'high']).default('medium'),
  email: z.string().email(),
  tags: z.array(z.string().max(30)).max(10).optional(),
});

export type CreateTicketInput = z.infer<typeof CreateTicket>;

The TypeScript type is inferred from the schema — one source of truth.

Middleware

const validate = (schema) => (req, res, next) => {
  const result = schema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json({ error: 'Invalid input', details: result.error.flatten() });
  }
  req.body = result.data;
  next();
};

app.post('/tickets', validate(CreateTicket), async (req, res) => {
  const ticket = await createTicket(req.body);
  res.status(201).json(ticket);
});

Query Strings and Params

Use z.coerce.number() for numeric query parameters, with sensible limits:

const ListQuery = z.object({ page: z.coerce.number().int().min(1).default(1), limit: z.coerce.number().max(100).default(20) });

Share With the Frontend

Put schemas in a shared package so forms and APIs use identical rules.

Validate AI Output Too

When an LLM returns JSON, parse it with a schema before using it. Models occasionally return unexpected shapes.

Alternatives

Valibot, ArkType, TypeBox, and JSON Schema (with Fastify) are good choices too.

Validation at the boundary keeps the inside of your application simple and safe.

Arivanandhan Chitheshwaran