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

javascriptsnippet
42 lines
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: ajv and ajv-formats are 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

FAQ

Does this require external packages?
Yes — `ajv` and `ajv-formats`. Add them to your project before running the snippet.