Express Zod Safe is a TypeScript-first middleware for Express.js applications, offering robust and typesafe validation of incoming HTTP request bodies, URL parameters, and query strings. It leverages Zod schemas to define validation rules, ensuring data integrity and preventing invalid or malicious data from reaching application logic. The current stable version is 3.2.1, which targets Zod v4.0.0 and above. While a specific release cadence isn't published, it appears to follow Zod's major version updates. Key differentiators include its strict type safety, seamless integration with the Express middleware stack, comprehensive coverage of request parts (body, params, query), and developer-friendly error handling, aiming to be a more robust alternative to similar packages like `zod-express-middleware`.
npm install express-zod-safeVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up an Express route with `express-zod-safe` to validate URL parameters, query strings, and the request body using Zod schemas, including basic error handling.
Ensure your installed `express-zod-safe` package matches the major version of your `zod` package. Upgrade `zod` to `^4.0.0` for `express-zod-safe@3.x.x` or downgrade `express-zod-safe` to `1.5.4` for `zod@3.x.x`.
Always ensure `app.use(express.json());` (or similar body parsing middleware) is called *before* any route or middleware that uses `express-zod-safe`'s `validate` function.
For query and path parameters that are expected to be numbers, booleans, or dates, use `z.coerce.number()`, `z.coerce.boolean()`, `z.coerce.date()`, etc., in your Zod schemas.
Ensure all properties (`params`, `query`, `body`) passed to `validate` are defined Zod schemas or empty objects (`z.object({})`) if not needed, instead of being `undefined`.Add `app.use(express.json());` (or `express.urlencoded()`) early in your middleware chain, ensuring it runs *before* any route handlers or middleware that use `express-zod-safe`.
Use the `ValidatedRequest` type from `express-zod-safe` to correctly type your Express `Request` object. For example: `app.post('/user', validate({ body: userSchema }), (req: ValidatedRequest<typeof userSchema>, res) => { ... });`