Add request validation middleware
Add request validation middleware to Express with a Zod schema, so handlers receive a checked body or the client gets a 400.
A middleware that validates the body keeps the check out of each handler. The route receives a parsed object, or never runs.
import express from 'express';
import { z } from 'zod';
const validate = (schema) => (req, res, next) => {
const result = schema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ errors: result.error.issues.map((i) => i.path.join('.')) });
}
req.body = result.data;
next();
};
const app = express();
app.use(express.json());
app.post('/users', validate(z.object({ name: z.string().min(1) })), (req, res) => {
res.status(201).json({ name: req.body.name });
});
const server = app.listen(0, async () => {
const url = `http://localhost:${server.address().port}/users`;
const send = (body) =>
fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
for (const body of [{ name: 'Ada' }, { name: '' }]) {
const res = await send(body);
console.log(res.status, await res.json());
}
server.close();
});201 { name: 'Ada' }
400 { errors: [ 'name' ] }validate(schema) returns the middleware, so each route names its own schema. Replacing req.body with result.data means the handler sees the parsed value, with unknown keys removed and defaults applied.
The same factory can check req.query or req.params. Return a stable error format rather than the raw Zod issues if clients depend on it. Express 5 is assumed; express.json() must run first or req.body is undefined.