CPCODELAB
Express

Input Validation

9 min read

Input Validation

Never trust data that arrives from the network. Input validation ensures that req.body, req.params, and req.query match the shape and constraints you expect before your business logic touches them.

The most popular validation libraries for Express are Zod (TypeScript-first), Joi, and express-validator. Zod is recommended for TypeScript projects because its inferred types propagate to the rest of your codebase.

js
import { z } from "zod";

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

app.post("/users", (req, res, next) => {
  const result = CreateUserSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(422).json({ errors: result.error.flatten() });
  }
  // result.data is typed and safe
  const { name, email, age } = result.data;
  res.status(201).json({ name, email, age });
});

A cleaner pattern is to extract validation into a reusable middleware factory. The factory accepts a schema and returns a middleware that parses req.body against it, either attaching the result to res.locals or calling next(err) on failure.

Validation is not the same as sanitisation. After validating that a field is a string, you may still need to strip HTML tags or escape special characters before storing or displaying it.

Ready to test yourself?
Practice Express— quiz & coding exercises