Back to results for “Express & Middleware”
Node.js › Express & Middleware

How would you implement request validation middleware in Express using a schema-validation library like Zod or Joi?

Advanced

Answer

Validation middleware defines an expected schema for the request body, query parameters, or route parameters, validates the incoming request against it before the route handler runs, and either calls next() if valid or responds with a 400 error detailing exactly what validation failed -- centralizing validation logic outside individual route handlers and ensuring route handlers can trust the shape of the data they receive.
const { z } = require('zod');

const createUserSchema = z.object({ email: z.string().email(), age: z.number().min(18) });

function validate(schema) {
  return (req, res, next) => {
    const result = schema.safeParse(req.body);
    if (!result.success) return res.status(400).json({ errors: result.error.issues });
    req.body = result.data;
    next();
  };
}

app.post('/users', validate(createUserSchema), createUserHandler);
Real-world example An API extracts request validation into a reusable Zod-schema-based middleware, letting every route handler assume incoming data already matches the expected shape, eliminating scattered manual validation checks (and their associated bugs) throughout the route handler code itself.

Common follow-ups: What's the benefit of validating and transforming data in a single middleware step rather than validating inline within each handler?;How would you handle validating nested or deeply structured request bodies with this same pattern?