{"id":18022,"library":"zod-express","title":"Zod Express Request Validation Middleware","description":"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.","status":"active","version":"0.0.8","language":"javascript","source_language":"en","source_url":"https://github.com/pshaddel/zod-express","tags":["javascript","express","zod","middleware","endpoint","validation","typescript"],"install":[{"cmd":"npm install zod-express","lang":"bash","label":"npm"},{"cmd":"yarn add zod-express","lang":"bash","label":"yarn"},{"cmd":"pnpm add zod-express","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides TypeScript type definitions for Express, essential for type-safe development with this middleware.","package":"@types/express","optional":false},{"reason":"The core web framework that this package integrates with as a middleware.","package":"express","optional":false},{"reason":"The schema declaration and validation library central to this package's functionality.","package":"zod","optional":false}],"imports":[{"note":"This package is designed for ESM and TypeScript; CommonJS `require` might lead to issues or require specific tsconfig/build settings.","wrong":"const { validateRequest } = require('zod-express');","symbol":"validateRequest","correct":"import { validateRequest } from 'zod-express';"},{"note":"Used for schemas containing async refinements or transformations. Ensure you await the middleware chain if using in an async context.","wrong":"import validateRequestAsync from 'zod-express';","symbol":"validateRequestAsync","correct":"import { validateRequestAsync } from 'zod-express';"},{"note":"Use this function if you intend to apply Zod's `transform` or `refine` methods to modify the request data after validation, not just check validity.","wrong":"import { validateRequest } from 'zod-express/process';","symbol":"processRequest","correct":"import { processRequest } from 'zod-express';"},{"note":"While used with zod-express, `z` itself is imported directly from the `zod` package, not `zod-express`.","symbol":"z","correct":"import { z } from 'zod';"}],"quickstart":{"code":"import express from 'express';\nimport { validateRequest } from 'zod-express';\nimport { z } from 'zod';\n\n// Create an express app\nconst app = express();\napp.use(express.json()); // Essential for parsing JSON bodies\n\n// Define an endpoint using express, zod and zod-express\napp.get(\"/:urlParameter/\", validateRequest({\n    params: z.object({\n      urlParameter: z.string(),\n    }),\n    body: z.object({\n      bodyKey: z.number(),\n    }),\n    query: z.object({\n      queryKey: z.string().length(64),\n    }),\n  }), (req, res) => {\n    // req.params, req.body and req.query are now strictly-typed and confirm to the zod schema's above.\n    // req.params has type { urlParameter: string };\n    // req.body has type { bodyKey: number };\n    // req.query has type { queryKey: string };\n    return res.json({message: \"Validation for params, body and query passed\", data: { params: req.params, body: req.body, query: req.query }});  \n  }\n);\n\n// Add a basic error handling middleware to catch ZodErrors\napp.use((err, req, res, next) => {\n  if (err instanceof z.ZodError) {\n    return res.status(400).json({ error: 'Validation failed', details: err.errors });\n  }\n  next(err);\n});\n\n// Start the express app on port 8080\nconst PORT = 8080;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n});\n","lang":"typescript","description":"Demonstrates defining an Express route with `validateRequest` middleware to validate URL parameters, request body, and query string against Zod schemas, including basic error handling."},"warnings":[{"fix":"Review release notes carefully for any breaking changes before upgrading. Pin exact versions (`^0.0.x` or `0.0.x`) to prevent unexpected breakage.","message":"As a relatively new package (v0.0.8) forked from another project, the API surface may still be subject to frequent changes and potential breaking modifications between minor or even patch versions. Exercise caution when upgrading.","severity":"breaking","affected_versions":"<=0.0.8"},{"fix":"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.","message":"The validation middlewares (`validateRequest`, `validateRequestBody`, etc.) will throw a `ZodError` if validation fails. Without an Express error-handling middleware, this can lead to unhandled promise rejections or generic server errors.","severity":"gotcha","affected_versions":">=0.0.1"},{"fix":"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.","message":"The `processRequest` (and related `processRequestBody`, etc.) functions will apply Zod transformations (`.transform()`) to the request data. This means `req.body`, `req.query`, or `req.params` might be modified, which can be unexpected if you only intended to validate.","severity":"gotcha","affected_versions":">=0.0.1"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"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`.","cause":"Incorrect import statement or attempting to use CommonJS `require()` syntax with an ESM-first package.","error":"TypeError: validateRequest is not a function"},{"fix":"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.","cause":"The incoming request data (body, query, or params) does not conform to the defined Zod schema.","error":"ZodError: Invalid input"},{"fix":"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.","cause":"This TypeScript error occurs when `req.body` (or `req.query`, `req.params`) is accessed after `validateRequest` but TypeScript hasn't correctly inferred the new, validated type. This often happens if the middleware isn't correctly typed or if the schema isn't fully captured by the `Request` type.","error":"Property 'bodyKey' does not exist on type 'Request'"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}