express-jsonschema
raw JSON → 1.1.6 verified Sat Apr 25 auth: no javascript maintenance
Express middleware for JSON Schema validation, currently at version 1.1.6. It leverages the jsonschema library to validate request bodies against JSON Schema v4. The library provides a simple validate() middleware that attaches validation results to req.validations. Error handling is left to the developer, allowing custom responses. Compared to express-validator or Joi, this library decouples validation logic from schema definitions. It is in maintenance mode, with the last release in 2016 and no recent updates.
Common errors
error TypeError: validate is not a function ↓
cause Attempted to use default import without destructuring.
fix
Use const { validate } = require('express-jsonschema');
error Cannot read property 'body' of undefined ↓
cause The validate() call is missing the request property key, e.g., validate({ body: schema }).
fix
Pass an object with key 'body', 'query', or 'params'.
Warnings
gotcha The validate() function expects an object with keys 'body', 'query', or 'params' - not just a schema object. ↓
fix Use validate({ body: schema }) instead of validate(schema).
gotcha Error handling must be explicitly implemented; unhandled validation errors will crash the app. ↓
fix Add Express error middleware checking for err.name === 'JsonSchemaValidation'.
deprecated The project has not been updated since 2016 and does not support modern Express versions (4.17+). ↓
fix Consider migrating to @express-validator/express-validator or joi-based middleware.
Install
npm install express-jsonschema yarn add express-jsonschema pnpm add express-jsonschema Imports
- validate wrong
const validate = require('express-jsonschema');correctconst validate = require('express-jsonschema').validate; - JsonSchemaValidation wrong
const { JsonSchemaValidation } = require('express-jsonschema');correctconst JsonSchemaValidation = require('express-jsonschema').JsonSchemaValidation; - validate (ESM) wrong
import validate from 'express-jsonschema';correctimport { validate } from 'express-jsonschema';
Quickstart
const express = require('express');
const { validate } = require('express-jsonschema');
const app = express();
app.use(require('body-parser').json());
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
},
required: ['name']
};
app.post('/user', validate({ body: schema }), (req, res) => {
res.json({ valid: true });
});
app.use((err, req, res, next) => {
if (err.name === 'JsonSchemaValidation') {
res.status(400).json({ errors: err.validations });
} else {
next(err);
}
});
app.listen(3000);