{"id":17093,"library":"express-json-validator-middleware","title":"Express JSON Validator Middleware","description":"express-json-validator-middleware is an Express middleware for validating incoming HTTP requests against JSON Schemas, leveraging the Ajv validator. It supports validation of `body`, `params`, `query`, or custom request properties. The current stable version is 4.0.0. The library's release cadence is often tied to significant upgrades of its underlying Ajv dependency or changes in supported Node.js and Express versions, with major versions frequently introducing breaking changes. Key differentiators include its flexible validation targets, generation of detailed error objects from Ajv that facilitate custom error handling, and robust TypeScript support for defining schemas. The primary goal is to abstract validation logic from route handlers, leading to more maintainable and expressive application code.","status":"active","version":"4.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/simonplend/express-json-validator-middleware","tags":["javascript","express","json","validate","validation","validator","typescript"],"install":[{"cmd":"npm install express-json-validator-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add express-json-validator-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add express-json-validator-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as a peer dependency for core Express middleware functionality.","package":"express","optional":false}],"imports":[{"note":"Since v4, the library targets Node.js 24+ and is primarily ESM-first. While CJS require might work for some destructuring, ESM imports are the recommended and most reliable approach.","wrong":"const Validator = require('express-json-validator-middleware').Validator;","symbol":"Validator","correct":"import { Validator } from 'express-json-validator-middleware';"},{"note":"This class is used to catch and handle validation errors within Express error-handling middleware.","wrong":"const { ValidationError } = require('express-json-validator-middleware');","symbol":"ValidationError","correct":"import { ValidationError } from 'express-json-validator-middleware';"},{"note":"A TypeScript type helper for combining with Ajv's JSONSchemaType, ensuring correct schema definition.","symbol":"AllowedSchema","correct":"import type { AllowedSchema } from 'express-json-validator-middleware';"}],"quickstart":{"code":"import express from \"express\";\nimport { Validator } from \"express-json-validator-middleware\";\n\nconst app = express();\n\n// Essential: This middleware parses incoming JSON requests into req.body\napp.use(express.json());\n\nconst addressSchema = {\n\ttype: \"object\",\n\trequired: [\"street\"],\n\tproperties: {\n\t\tstreet: {\n\t\t\ttype: \"string\",\n\t\t\tminLength: 3\n\t\t}\n\t},\n\tadditionalProperties: false\n};\n\n// Instantiate the validator and destructure the 'validate' function\nconst { validate } = new Validator({ allErrors: true });\n\napp.post(\"/address\", validate({ body: addressSchema }), (request, response) => {\n\t// If validation passes, request.body is guaranteed to match addressSchema\n\tresponse.status(200).json({ receivedStreet: request.body.street });\n});\n\n// Global error handler for validation errors\napp.use((error, request, response, next) => {\n\tif (error instanceof Validator.ValidationError) {\n\t\tconsole.error(\"Validation Error:\", error.validationErrors);\n\t\tresponse.status(400).json({\n\t\t\tname: error.name,\n\t\t\tvalidationErrors: error.validationErrors\n\t\t});\n\t\treturn;\n\t}\n\tnext(error);\n});\n\nconst PORT = process.env.PORT ?? 3000;\napp.listen(PORT, () => {\n  console.log(`Server listening on port ${PORT}`);\n});","lang":"typescript","description":"This example demonstrates how to set up an Express application, initialize the validator, define a JSON schema for a request body, apply the validation middleware to a route, and implement a global error handler for `ValidationError` instances. It ensures `express.json()` is used for body parsing."},"warnings":[{"fix":"Upgrade your Node.js runtime to version 24.0.0 or newer, and your Express dependency to `^4.21.2` or `^5.2.1`.","message":"Version 4.0.0 introduces updated runtime requirements, mandating Node.js >=24.0.0 and specific Express versions (4.21.2+ or 5.2.1+). Applications running on older environments will not be compatible.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Review your existing JSON schemas against the Ajv v8 migration guide to ensure continued compatibility and correct validation behavior.","message":"Version 3.0.0 upgraded the underlying Ajv library to v8. This update can introduce breaking changes in how JSON schemas are interpreted or validated. Consult the Ajv v8 migration guide for details.","severity":"breaking","affected_versions":">=3.0.0 <4.0.0"},{"fix":"Consult the Ajv v5 migration guide and verify your JSON schemas for any required adjustments.","message":"Version 1.1.0 upgraded the underlying Ajv library to v5. Similar to subsequent major Ajv upgrades, this could necessitate changes to your JSON schemas.","severity":"breaking","affected_versions":">=1.1.0 <3.0.0"},{"fix":"Ensure you add `app.use(express.json());` (and/or `express.urlencoded()`) early in your middleware chain, before any routes that use body validation.","message":"The `express-json-validator-middleware` relies on Express's body parsing middleware (e.g., `express.json()`) to populate `req.body`. Without it, body validation will fail because `req.body` will be undefined.","severity":"gotcha","affected_versions":"*"},{"fix":"Remove any explicit `.bind(validator)` calls on the `validate` function, as it is now automatically bound.","message":"As of v1.1.1, the `.validate` method is automatically bound to the `Validator` instance. Manual binding (e.g., `.bind(validator)`) is no longer necessary and should be removed.","severity":"gotcha","affected_versions":">=1.1.1"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Add `app.use(express.json());` to your Express application before defining routes that process JSON bodies.","cause":"The `express.json()` middleware was not used, so `req.body` is undefined when the route handler attempts to access its properties.","error":"TypeError: Cannot read properties of undefined (reading 'street')"},{"fix":"Ensure you are calling the `validate` function with your schema object, e.g., `validate({ body: addressSchema })`, and passing the *result* to the Express route handler.","cause":"The `validate` function from `express-json-validator-middleware` was not called. Instead, a plain schema object was passed directly to the Express route.","error":"TypeError: Router.use() requires a middleware function but got a Object"},{"fix":"Prefer `import { Validator } from 'express-json-validator-middleware';` in an ESM module (recommended for Node.js 24+). If strictly using CJS, ensure correct destructuring: `const { Validator } = require('express-json-validator-middleware');`.","cause":"Attempting to `require` the `Validator` class in a CommonJS context when the library is primarily designed for ESM, or using incorrect CommonJS destructuring.","error":"TypeError: Validator is not a constructor"},{"fix":"Ensure you use `const { validate } = new Validator({ ... });` to correctly extract the method.","cause":"The `validate` function was not correctly destructured from the `Validator` instance after instantiation.","error":"ReferenceError: validate is not defined"}],"ecosystem":"npm","meta_description":null}