Registry / web-framework / express-json-validator-middleware

express-json-validator-middleware

JSON →
library4.0.0jsnpmunverified

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-middleware
INSTALL
IMPORT
SIG · EXPRESS-JSON-VALID
E
express-json-validator-middleware
web-frameworkjavascriptv4.0.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.

Validator
import { Validator } from 'express-json-validator-middleware';
const Validator = require('express-json-validator-middleware').Validator;
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.
ValidationError
import { ValidationError } from 'express-json-validator-middleware';
const { ValidationError } = require('express-json-validator-middleware');
This class is used to catch and handle validation errors within Express error-handling middleware.
AllowedSchema
import type { AllowedSchema } from 'express-json-validator-middleware';
A TypeScript type helper for combining with Ajv's JSONSchemaType, ensuring correct schema definition.

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.

import express from "express"; import { Validator } from "express-json-validator-middleware"; const app = express(); // Essential: This middleware parses incoming JSON requests into req.body app.use(express.json()); const addressSchema = { type: "object", required: ["street"], properties: { street: { type: "string", minLength: 3 } }, additionalProperties: false }; // Instantiate the validator and destructure the 'validate' function const { validate } = new Validator({ allErrors: true }); app.post("/address", validate({ body: addressSchema }), (request, response) => { // If validation passes, request.body is guaranteed to match addressSchema response.status(200).json({ receivedStreet: request.body.street }); }); // Global error handler for validation errors app.use((error, request, response, next) => { if (error instanceof Validator.ValidationError) { console.error("Validation Error:", error.validationErrors); response.status(400).json({ name: error.name, validationErrors: error.validationErrors }); return; } next(error); }); const PORT = process.env.PORT ?? 3000; app.listen(PORT, () => { console.log(`Server listening on port ${PORT}`); });
Debug
Known issues
breakingVersion 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.
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`.
affects: >=4.0.0
breakingVersion 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.
fix
Review your existing JSON schemas against the Ajv v8 migration guide to ensure continued compatibility and correct validation behavior.
affects: >=3.0.0 <4.0.0
breakingVersion 1.1.0 upgraded the underlying Ajv library to v5. Similar to subsequent major Ajv upgrades, this could necessitate changes to your JSON schemas.
fix
Consult the Ajv v5 migration guide and verify your JSON schemas for any required adjustments.
affects: >=1.1.0 <3.0.0
gotchaThe `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.
fix
Ensure you add `app.use(express.json());` (and/or `express.urlencoded()`) early in your middleware chain, before any routes that use body validation.
affects: *
gotchaAs 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.
fix
Remove any explicit `.bind(validator)` calls on the `validate` function, as it is now automatically bound.
affects: >=1.1.1
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'street')
The `express.json()` middleware was not used, so `req.body` is undefined when the route handler attempts to access its properties.
fix
Add `app.use(express.json());` to your Express application before defining routes that process JSON bodies.
TypeError: Router.use() requires a middleware function but got a Object
The `validate` function from `express-json-validator-middleware` was not called. Instead, a plain schema object was passed directly to the Express route.
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.
TypeError: Validator is not a constructor
Attempting to `require` the `Validator` class in a CommonJS context when the library is primarily designed for ESM, or using incorrect CommonJS destructuring.
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');`.
ReferenceError: validate is not defined
The `validate` function was not correctly destructured from the `Validator` instance after instantiation.
fix
Ensure you use `const { validate } = new Validator({ ... });` to correctly extract the method.
Upgrade
Version history
4.0.0latest on npm
Audit
Dependencies
expressrequiredRequired as a peer dependency for core Express middleware functionality.
Agent activity
2 hits · last 30 days
node
2
Resources