AJV OpenAPI Schema Validation Middleware
Validate request bodies against JSON Schema compiled with AJV using OpenAPI component schemas, with fast paths and collected error details.
Code
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
const ajv = new Ajv({ allErrors: true, coerceTypes: true, removeAdditional: true });
addFormats(ajv);
const schemas = {
CreateUser: {
type: 'object',
additionalProperties: false,
required: ['email', 'role'],
properties: {
email: { type: 'string', format: 'email' },
role: { type: 'string', enum: ['admin', 'editor', 'viewer'] },
display_name: { type: 'string', maxLength: 60 },
},
},
};
const validate = ajv.compile({
$ref: '#/components/schemas/CreateUser',
components: { schemas },
});
function schemaMiddleware(validator) {
return (req, res, next) => {
if (!validator(req.body)) {
return res.status(400).json({
error: 'schema validation failed',
details: (validator.errors ?? []).map((e) => ({
path: e.instancePath || e.params?.missingProperty ?? '',
message: e.message,
})),
});
}
next();
};
}
const ok = validate({ email: 'ada@example.com', role: 'editor' });
const bad = validate({ email: 'not-an-email', role: 'hacker', extra: 1 });
console.log('valid:', ok, 'errors:', bad ? 0 : validate.errors.length);How the snippet works
AJV OpenAPI Schema Validation Middleware keeps everything in the function schemaMiddleware.
Watch out for
- Plan for an install step:
ajvandajv-formatsare a real dependency, resolved by the package manager.
Applying it
The main signature reads function schemaMiddleware(validator)
Output lines are prefixed (valid:), making each step’s effect easy to spot.
Statements that matter
details: (validator.errors ?? []).map((e) => ({
path: e.instancePath || e.params?.missingProperty ?? '',
message: e.message,
})),
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.
FAQ
- Does this require external packages?
- Yes — `ajv` and `ajv-formats`. Add them to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.