Express Zod Request Validation
Validate Express request body, params, and query with Zod schemas via reusable middleware.
import { Request, Response, NextFunction } from 'express';
import { ZodSchema, ZodError } from 'zod';
export function validate(schema: ZodSchema) {
return (req: Request, res: Response, next: NextFunction) => {
try {
schema.parse({
body: req.body,
query: req.query,
params: req.params,
});
next();
} catch (err) {
if (err instanceof ZodError) {
res.status(400).json({
error: 'Validation failed',
issues: err.issues.map((i) => ({
path: i.path.join('.'),
message: i.message,
})),
});
return;
}
next(err);
}
};
}Use Cases
- API input validation
- Form submission handling
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.
Environment Variable Validator
Validates required environment variables at startup and returns a typed config object or throws with missing keys.