Express JSON Validator Middleware

4.0.0 · active · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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}`);
});

view raw JSON →