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.
npm install express-json-validator-middlewareVerified import paths — ran on the pinned version, not inferred.
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.
Upgrade your Node.js runtime to version 24.0.0 or newer, and your Express dependency to `^4.21.2` or `^5.2.1`.
Review your existing JSON schemas against the Ajv v8 migration guide to ensure continued compatibility and correct validation behavior.
Consult the Ajv v5 migration guide and verify your JSON schemas for any required adjustments.
Ensure you add `app.use(express.json());` (and/or `express.urlencoded()`) early in your middleware chain, before any routes that use body validation.
Remove any explicit `.bind(validator)` calls on the `validate` function, as it is now automatically bound.
Add `app.use(express.json());` to your Express application before defining routes that process JSON bodies.
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.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');`.Ensure you use `const { validate } = new Validator({ ... });` to correctly extract the method.