typescriptbeginner
Express Zod Request Validation
Validate Express request body, params, and query with Zod schemas via reusable middleware.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptintermediate
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
Best for: REST API authentication
#jwt#express
typescriptintermediate
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Best for: API abuse prevention
#express#rate-limit
typescriptbeginner
Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.
Best for: Express route error handling
#express#async
typescriptintermediate
Express Error Handling Middleware
Centralized error handling in Express with custom error classes, async wrapper, and structured responses.
Best for: API error standardization
#nodejs#express