Full answer
The middleware pattern
- validate(schema, 'body') returns (req, res, next) => { ... }. On success, store the clean data and call next(). On failure, send a 400 or 422 response with a compact list of issues and do not call next().
- Keep the response format the same for all routes (see error format items).
- Handlers then read from res.locals.body (the parsed data) and not from req.body.
Details that matter
- In Express 5 req.query is a getter that is computed on each access, so you cannot assign a new value to it. Store the parsed query in res.locals (or a custom property).
- Query values are strings. Use z.coerce.number() or transform for page and limit, and set limits: z.coerce.number().int().min(1).max(100).default(20).
- Mass assignment: if you pass req.body to an update call, a client can set fields such as role or isAdmin. Parse with an object schema that lists only allowed fields. The default strips unknown keys. Use strictObject when you want to reject them.
- Validate params (ids) too: z.coerce.number().int().positive().
- Keep body size limits on express.json({ limit: '100kb' }). Validation comes after parsing, so it cannot protect memory.
- Do not expose internals. Return path and message for each issue, not stack traces.
- For documentation and typing, the same schemas can generate OpenAPI (zod-to-openapi style libraries) or TypeScript types.
Fastify has built-in JSON Schema validation (ajv). With zod you can use a type provider.
const express = require('express');
const { z } = require('zod');
const validate = (schema, where) => (req, res, next) => {
const result = schema.safeParse(req[where]);
if (!result.success) {
return res.status(400).json({
error: 'validation_failed',
issues: result.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message })),
});
}
res.locals[where] = result.data; // parsed data lives here, req.query is read-only in Express 5
next();
};
const CreateUser = z.object({ name: z.string().min(2), email: z.email() }); // role is not allowed
const ListQuery = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(50).default(10),
});
const users = [];
const app = express();
app.use(express.json({ limit: '10kb' }));
app.post('/users', validate(CreateUser, 'body'), (req, res) => {
const user = { id: users.length + 1, ...res.locals.body, role: 'student' }; // role is set by the server
users.push(user);
res.status(201).json(user);
});
app.get('/users', validate(ListQuery, 'query'), (req, res) => {
const { page, limit } = res.locals.query;
res.json({ page, limit, total: users.length });
});
const server = app.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
const post = (body) => fetch(base + '/users', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
let res = await post({ name: 'Asha', email: 'asha@example.com', role: 'admin' });
console.log('create with role=admin ->', res.status, JSON.stringify(await res.json()));
res = await post({ name: 'A', email: 'x' });
console.log('invalid body ->', res.status, JSON.stringify(await res.json()));
res = await fetch(base + '/users?page=2&limit=5');
console.log('query coerced ->', JSON.stringify(await res.json()));
res = await fetch(base + '/users?limit=500');
console.log('limit too large ->', res.status, JSON.stringify((await res.json()).issues));
server.close();
});An Express app validates body and query data. The client tries to set role=admin, which is dropped, and sends bad values, which are rejected. Install first with npm install express zod (run here with express 5.3.0, zod 4.6.7). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): create with role=admin -> 201 {"id":1,"name":"Asha","email":"asha@example.com","role":"student"} invalid body -> 400 {"error":"validation_failed","issues":[{"field":"name","message":"Too small: expected string to have >=2 characters"},{"field":"email","message":"Invalid email address"}]} query coerced -> {"page":2,"limit":5,"total":1} limit too large -> 400 [{"field":"limit","message":"Too big: expected number to be <=50"}]
Key points
- Middleware factory: validate(schema, where).
- Store parsed data separately from the raw request.
- Express 5 req.query cannot be reassigned.
- Strip or reject unknown fields to stop mass assignment.
- Validate params and query, not only the body.
Common mistakes
- Passing req.body straight to the database.
- Trying to assign req.query in Express 5.
- Forgetting to coerce query numbers, which arrive as strings.
- Different error shapes on different routes.
- Relying on validation to limit request size.
Follow-ups
- How would you validate a nested array of items?
- How does Fastify do validation without middleware?
- How do you share one schema between server and client?
Tips
- Describe the factory function first.
- Mention mass assignment by name.
- Mention the Express 5 req.query detail.