Intermediate LevelExpress JS
How do you implement robust request body, query, and param validation using Zod middleware in Express?
❓ Interview Prompt: Explain request validation middleware, Zod schema parsing, validating req.body/params/query, and returning 400 Bad Request error lists.
Relying on manual 'if (!req.body.name)' checks in controllers leads to repetitive, bug-prone code.
Zod Validation Middleware:
Write a reusable higher-order middleware function that accepts a Zod schema and validates incoming 'req.body', 'req.query', or 'req.params'. If validation fails, return a 400 Bad Request response formatted with precise Zod error messages!
Code Implementation Example
javascript
import { z } from 'zod';
const createUserSchema = z.object({
body: z.object({
email: z.string().email('Invalid email address'),
age: z.number().min(18, 'Must be at least 18 years old')
})
});
export const validate = (schema) => (req, res, next) => {
try {
schema.parse({ body: req.body, query: req.query, params: req.params });
next();
} catch (error) {
res.status(400).json({ errors: error.errors });
}
};
// Usage: app.post('/users', validate(createUserSchema), controller);💡Generic request input validation middleware using Zod schemas.
🎯 Interview Key Takeaway
Use Zod validation middleware to validate request bodies, params, and queries before reaching route controllers.
#Zod#Validation#Middleware#Intermediate
Back to all Express JS Questions→