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.

JavascriptNodeData Integrity

Code

snippet
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: '[email protected]', role: 'editor' });
const bad = validate({ email: 'not-an-email', role: 'hacker', extra: 1 });
console.log('valid:', ok, 'errors:', bad ? 0 : validate.errors.length);