OpenAPI Enforcer Middleware

raw JSON →
2.2.0 verified Sat Apr 25 auth: no javascript

Express middleware that leverages your OpenAPI document to automatically validate requests and responses, mock responses in development, and route requests to your controller functions. Version 2.2.0 supports OpenAPI 2.0 and 3.0.x. Requires openapi-enforcer (>=1.2.0) and express (>=4.0.0) as peer dependencies. Compared to alternatives like express-openapi-validator, this middleware enforces both request and response validation, and offers built-in mocking. Ships TypeScript types. Releases are stable with periodic updates.

error TypeError: OpenApiEnforcerMiddleware is not a constructor
cause Using CommonJS require() on ESM-only package
fix
Use import { OpenApiEnforcerMiddleware } from 'openapi-enforcer-middleware' with 'type': 'module' in package.json or run with --experimental-modules.
error Error: Cannot find module 'openapi-enforcer'
cause Missing peer dependency openapi-enforcer
fix
Run npm install openapi-enforcer openapi-enforcer-middleware.
breaking Importing with require() fails because package is ESM-only since v2
fix Use 'import' syntax or dynamic import().
deprecated The 'OpenApiEnforcerMiddleware' constructor no longer accepts a string path to the OpenAPI document directly; it must be a resolved object
fix Use the 'start()' method to resolve the document.
gotcha Middleware must be applied after calling enforcer.start()
fix Always await enforcer.start() before using enforcer.middleware().
gotcha Response validation may cause false positives if error headers or status codes are not present in the OpenAPI spec
fix Add all possible response schemas to your OpenAPI document or disable response validation with option validateResponse: false.
gotcha Mock mode returns generated data based on schema but might not be production-ready
fix Disable mock mode in production production: set mock: false.
npm install openapi-enforcer-middleware
yarn add openapi-enforcer-middleware
pnpm add openapi-enforcer-middleware

Shows initializing OpenApiEnforcerMiddleware with an OpenAPI file, starting the enforcer, applying middleware, and defining a route that matches an operationId.

import express from 'express';
import { OpenApiEnforcerMiddleware } from 'openapi-enforcer-middleware';

const app = express();

const enforcer = new OpenApiEnforcerMiddleware('./openapi.yaml', {
  mock: true, // enables mocks in development
});

// Resolve the OpenAPI document
await enforcer.start();

// Use the middleware
app.use(enforcer.middleware());

// Define a controller (function name must match operationId in OpenAPI)
app.get('/users/:id', (req, res) => {
  res.json({ id: req.params.id, name: 'John' });
});

app.listen(3000, () => console.log('Server running on port 3000'));