Script Valley
REST API Development: Beginner to Production
Data Validation, Error Handling, and API Design PatternsLesson 3.1

Input validation in Express with Zod

Zod schema, z.object, z.string, z.number, safeParse, validation middleware, error formatting, required vs optional fields

Input Validation with Zod

Never trust user input. Validate every incoming request body, query parameter, and route parameter before touching your database or business logic. Zod is the cleanest validation library for Node.js โ€” schemas are type-safe and parse, they don't just check.

Install and Define a Schema

npm install zod
// validation/userSchema.js
const { z } = require('zod');

const createUserSchema = z.object({
  name: z.string().min(1).max(100),
  email: z.string().email(),
  age: z.number().int().min(0).max(150).optional()
});

module.exports = { createUserSchema };

Validation Middleware

// middleware/validate.js
const validate = (schema) => (req, res, next) => {
  const result = schema.safeParse(req.body);
  if (!result.success) {
    return res.status(422).json({
      errors: result.error.errors.map(e => ({
        field: e.path.join('.'),
        message: e.message
      }))
    });
  }
  req.validatedBody = result.data;
  next();
};

module.exports = validate;
// In your route
router.post('/users', validate(createUserSchema), createUser);

Use safeParse not parse โ€” safeParse returns a result object instead of throwing, which works cleanly with middleware. Attach the parsed data to req.validatedBody so controllers use the coerced, validated value rather than raw input.

Up next

Consistent API error response format design

Sign in to track progress

Input validation in Express with Zod โ€” Data Validation, Error Handling, and API Design Patterns โ€” REST API Development: Beginner to Production โ€” Script Valley โ€” Script Valley