zod-express is an Express.js middleware designed for robust request validation using Zod schemas. Currently at version 0.0.8, this package provides functions like `validateRequest` and `processRequest` to ensure incoming `req.body`, `req.query`, and `req.params` conform to predefined Zod schemas, offering compile-time type safety in TypeScript environments. It recently introduced support for asynchronous validators. `zod-express` is a fork of `zod-express-middleware`, aiming to provide a maintained solution for this use case. Its release cadence appears to be driven by new features or bug fixes, rather than a strict schedule, as indicated by the recent `0.0.8` release adding async validation. Key differentiators include its focus on strong typing with Zod and the flexibility to either just validate or validate and transform/process request data.
npm install zod-expressVerified import paths — ran on the pinned version, not inferred.
Demonstrates defining an Express route with `validateRequest` middleware to validate URL parameters, request body, and query string against Zod schemas, including basic error handling.
Review release notes carefully for any breaking changes before upgrading. Pin exact versions (`^0.0.x` or `0.0.x`) to prevent unexpected breakage.
Implement a custom error-handling middleware in Express (e.g., `app.use((err, req, res, next) => { if (err instanceof z.ZodError) { return res.status(400).json({ errors: err.errors }); } next(err); });`) to gracefully handle validation failures.Use `validateRequest` for validation-only scenarios where request data should remain untouched. Only use `processRequest` when you explicitly intend to modify the request data based on Zod transformations.
Ensure you are using `import { validateRequest } from 'zod-express';` at the top of your file. If using CommonJS, check your `tsconfig.json` for `"module": "NodeNext"` or `"type": "module"` in `package.json`.Inspect the `err.errors` array within your Express error-handling middleware to get detailed validation messages. Adjust the client-side data or refine your Zod schema to match expected inputs.
Ensure your Express app's request handler is correctly typed to leverage the `zod-express` middleware's type augmentation. Sometimes explicitly casting `req` or using a generic `Request<P, ResBody, ReqBody, ReqQuery>` with your schema's inferred type can resolve this, though `zod-express` aims to handle this automatically.