Registry / web-framework / zod-express-middleware

zod-express-middleware

JSON →
library1.4.0jsnpmunverified

`zod-express-middleware` is an Express.js middleware library designed to enforce type safety and validate incoming request data (body, query, and parameters) using Zod schemas. Currently at version 1.4.0, it provides functions like `validateRequest` to check if an incoming request conforms to predefined Zod schemas without modifying the request object. For scenarios requiring data transformation or stripping unknown keys, it offers `processRequest` and its specific variants (`processRequestBody`, `processRequestQuery`, `processRequestParams`), which leverage Zod's `.transform` and `.refine` methods. The package maintains a steady release cadence, integrating smoothly with `express` and `zod` as peer dependencies. Its primary differentiator is the direct integration of Zod's powerful, inferential schema validation capabilities into the Express middleware pipeline, providing a robust solution for ensuring API contract adherence and improving developer experience through strong typing.

npm install zod-express-middleware
INSTALL
IMPORT
SIG · ZOD-EXPRESS-MIDDLE
Z
zod-express-middleware
web-frameworkjavascriptv1.4.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

validateRequest
import { validateRequest } from 'zod-express-middleware';
const { validateRequest } = require('zod-express-middleware');
The library primarily uses ES Modules. While CommonJS `require` might work in some transpiled environments, native ESM `import` is the recommended and type-safe approach. `validateRequest` is the main entry point for combining body, query, and params validation.
processRequest
import { processRequest } from 'zod-express-middleware';
import { validateRequest } from 'zod-express-middleware'; // Used for transformations
Use `processRequest` (or its specific variants like `processRequestBody`) when you need to apply Zod transformations (`.transform()`, `.refine()`) to the request data, as `validateRequest` only performs validation without modifying the request object.
z
import { z } from 'zod';
Although `zod-express-middleware` uses Zod internally, `z` itself must be imported directly from the `zod` package to define your schemas. This is a crucial peer dependency.
TypedRequestBody
import { TypedRequestBody } from 'zod-express-middleware';
For explicit type annotations, especially when separating endpoint logic from route definitions, `TypedRequestBody`, `TypedRequestQuery`, `TypedRequestParams`, and `TypedRequest` are provided. Pass the `typeof` your Zod schema into these types.

This example demonstrates how to set up an Express application with `zod-express-middleware` to validate `req.params`, `req.body`, and `req.query` using Zod schemas for a POST endpoint. It includes basic Express setup, JSON body parsing, and a global error handler for Zod validation failures.

import express from 'express'; import { validateRequest } from 'zod-express-middleware'; import { z } from 'zod'; // Create an express app const app = express(); // Add express.json() middleware to parse JSON bodies app.use(express.json()); // Define an endpoint using express, zod and zod-express-middleware app.post("/:urlParameter/", validateRequest({ params: z.object({ urlParameter: z.string().uuid("Invalid URL parameter format"), }), body: z.object({ bodyKey: z.number().int().positive("bodyKey must be a positive integer"), optionalField: z.string().optional() }), query: z.object({ queryKey: z.string().length(64, "queryKey must be 64 characters long"), }), }), (req, res) => { // req.params, req.body and req.query are now strictly-typed and confirm to the zod schema's above. // req.params has type { urlParameter: string }; // req.body has type { bodyKey: number; optionalField?: string }; // req.query has type { queryKey: string }; console.log('Validated Params:', req.params); console.log('Validated Body:', req.body); console.log('Validated Query:', req.query); return res.json({message: "Validation for params, body and query passed", data: { params: req.params, body: req.body, query: req.query }}); } ); app.get('/', (req, res) => { res.send('Welcome to the Zod Express Middleware example!'); }); // Error handling middleware for ZodErrors app.use((err, req, res, next) => { if (err instanceof z.ZodError) { return res.status(400).json({ status: 'error', message: 'Validation failed.', errors: err.errors.map(e => ({ path: e.path.join('.'), message: e.message })) }); } next(err); }); // Start the express app on port 8080 const PORT = process.env.PORT ?? 8080; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); console.log('Try POST to /<uuid-param>?queryKey=... (64 chars) with JSON body { "bodyKey": 123 }'); });
Debug
Known issues
gotchaThis package relies on `express`, `zod`, and `@types/express` as peer dependencies. Failure to install these or installing incompatible versions will lead to runtime errors or TypeScript compilation issues.
fix
Ensure you have `express`, `zod`, and `@types/express` installed alongside `zod-express-middleware` with compatible versions (e.g., `npm install express zod @types/express` or verify your `package.json` for correct ranges).
affects: >=0.2.0
gotcha`validateRequest` and its variants only perform validation and do not modify the `req.body`, `req.query`, or `req.params` objects to reflect parsed or transformed values. If you need to apply Zod's `.transform()` or `.refine()` methods that alter the data, you must use the `processRequest` functions (e.g., `processRequest`, `processRequestBody`).
fix
If your Zod schema includes `.transform()` or `.refine()` and you expect the request object properties to be modified, switch from `validateRequest` to `processRequest` (or `processRequestBody`, etc.).
affects: >=0.2.0
gotchaThe default error messages provided by Zod for validation failures might be too technical for end-users. You'll likely need to implement custom error handling to present more user-friendly messages.
fix
Implement a custom Express error-handling middleware that catches `z.ZodError` instances and formats the `err.errors` array into a user-friendly response. Zod allows customizing messages directly in schema definitions or via a global error map.
affects: >=0.2.0
deprecatedAs of June 17, 2021, the repository maintainer noted that the project is not likely to receive significant updates in the future, suggesting alternatives like `express-zod-api` or `express-zod-safe` for new projects seeking more active development and features.
fix
For new projects or if you require more advanced features and active maintenance, consider migrating to `express-zod-api` or `express-zod-safe`. For existing projects, `zod-express-middleware` will continue to function as a simple, unopinionated solution.
affects: >=1.0.0
breakingRecent Zod versions (e.g., 3.25.76 and higher) can bundle Zod 4 code, which uses TypeScript 5+ syntax. This can cause build failures for projects still on TypeScript 4.x, even when `zod-express-middleware` itself has not updated its direct dependencies, due to `zod` being a peer dependency.
fix
Upgrade your project's TypeScript version to 5.x or higher to be compatible with newer Zod releases. Alternatively, you may need to pin your `zod` dependency to `~3.25.x` (e.g., `3.25.0` to `3.25.75`) if you cannot upgrade TypeScript.
affects: >=3.25.76 (of Zod peer dependency)
Errors
Common errors & fixes
Cannot find module 'express' or 'zod'
One of the peer dependencies (express or zod) is not installed or incorrectly configured in the project.
fix
Ensure `express` and `zod` are explicitly installed in your project: `npm install express zod`.
Property 'body' does not exist on type 'Request<ParamsDictionary, any, any, QueryString.ParsedQs, Record<string, any>>'.
TypeScript cannot infer the types of `req.body`, `req.query`, or `req.params` because `@types/express` is missing or the validation middleware is not correctly applied in a TypeScript environment.
fix
Install `@types/express`: `npm install --save-dev @types/express`. Ensure your route handler is defined immediately after `validateRequest` so TypeScript can infer the request object's updated type.
ZodError: Validation failed
The incoming request data (body, query, or params) does not conform to the defined Zod schema.
fix
Review the `err.errors` array within the `ZodError` instance to understand which fields failed validation and why. Adjust the incoming request data or refine your Zod schema to match expected inputs. Implement a custom error handler to return specific validation messages to the client.
TypeError: Cannot read properties of undefined (reading 'someProperty')
Attempting to access properties on `req.body`, `req.query`, or `req.params` before `express.json()`, `express.urlencoded()`, or `express.query()` middleware has parsed the respective part of the request, or when a property is missing and not explicitly `optional()` in the schema.
fix
Ensure that appropriate Express body-parsing middleware (`app.use(express.json())`, `app.use(express.urlencoded({ extended: true }))`) is applied *before* the `zod-express-middleware` in your Express app. Also, mark optional fields in your Zod schema with `.optional()` or `.nullable()`.
Upgrade
Version history
1.4.0latest on npm
Audit
Dependencies
@types/expressoptionalProvides TypeScript type definitions for Express.js, essential for type-safe usage.
expressrequiredThe core web framework that this package extends with middleware.
zodrequiredThe primary schema declaration and validation library used for defining request schemas.
Agent activity
52 hits · last 30 days
node
44
OpenAI (training)
1
Resources
zod-express-middleware — npm install zod-express-middleware · libregistry