Registry /
http-networking / openapi-validator-middleware
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
validator object (default export)
✓ import validator from 'openapi-validator-middleware';
✗ import { init, validate } from 'openapi-validator-middleware';
The package uses a CommonJS default export which maps to an ESM default import. All main functions (init, validate) and the InputValidationError class are properties of this exported object.
validator (CommonJS require)
✓ const validator = require('openapi-validator-middleware');
✗ const { validate } = require('openapi-validator-middleware');
This is the standard CommonJS import pattern. Functions and error class are accessed as properties of the `validator` object.
InputValidationError
✓ import validator from 'openapi-validator-middleware'; const { InputValidationError } = validator;
✗ import { InputValidationError } from 'openapi-validator-middleware';
The InputValidationError class is a property of the default-exported validator object, and should be destructured from it or accessed directly via `validator.InputValidationError`.
This quickstart demonstrates how to set up `openapi-validator-middleware` with an Express application. It initializes the validator with a dummy OpenAPI 3.0 specification file, applies the `validator.validate()` middleware to a route, and includes basic error handling for `InputValidationError`.
import express from 'express';
import path from 'path';
import validator from 'openapi-validator-middleware';
const app = express();
const PORT = process.env.PORT || 3000;
// Dummy OpenAPI spec for demonstration
const swaggerSpecPath = path.resolve('./swagger.yaml');
// In a real app, this would be a real file:
// fs.writeFileSync(swaggerSpecPath, `
// openapi: 3.0.0
// info:
// title: Test API
// version: 1.0.0
// paths:
// /users:
// post:
// requestBody:
// required: true
// content:
// application/json:
// schema:
// type: object
// properties:
// name:
// type: string
// email:
// type: string
// format: email
// required:
// - name
// - email
// responses:
// '200':
// description: User created
// `);
// In a real application, ensure the OpenAPI file exists.
// For this example, we'll initialize without reading a file directly
// to focus on the middleware usage, but you'd normally point to your spec.
// For simplicity, we'll manually define a schema here.
// In a real scenario, you would initialize with a path to your spec file:
// validator.init(swaggerSpecPath, { source: 'fs' });
// Simulate initialization with an in-memory spec if no file is present
// For a real setup, provide a path to your YAML/JSON OpenAPI spec.
const inMemorySpec = {
openapi: '3.0.0',
info: { title: 'Test API', version: '1.0.0' },
paths: {
'/users': {
post: {
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' }
},
required: ['name', 'email']
}
}
}
},
responses: { '200': { description: 'User created' } }
}
}
}
};
// NOTE: In a real scenario, you'd call validator.init(pathToSwaggerFile)
// We simulate by directly setting the internal schema for demonstration.
// This part is for demonstration only, the library expects a file path.
console.warn('Initializing openapi-validator-middleware without a physical file for demo. Provide a path to your spec in a real app.');
// A more realistic init would be:
// try {
// await validator.initAsync(swaggerSpecPath);
// } catch (error) {
// console.error('Failed to initialize validator:', error.message);
// process.exit(1);
// }
// This requires manually mocking the internal state, not directly possible via public API.
// So, for a runnable quickstart, we need an actual OpenAPI file.
// Let's create a minimal one for the example.
const fs = require('fs');
const swaggerContent = `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users:
post:
summary: Create a new user
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name:
type: string
minLength: 3
email:
type: string
format: email
required:
- name
- email
responses:
'201':
description: User created successfully
'400':
description: Invalid input
`;
fs.writeFileSync(swaggerSpecPath, swaggerContent);
validator.init(swaggerSpecPath);
app.use(express.json()); // Body parser middleware
app.post('/users', validator.validate(), (req, res) => {
// If validation passes, process the request
res.status(201).json({ message: 'User created', data: req.body });
});
// Error handling middleware for validation errors
app.use((err, req, res, next) => {
if (err instanceof validator.InputValidationError) {
return res.status(400).json({
message: 'Validation Error',
errors: err.errors,
validationContext: err.validationContext
});
}
next(err);
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Test with: curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com"}' http://localhost:${PORT}/users`);
console.log(`Test validation failure with: curl -X POST -H "Content-Type: application/json" -d '{"name": "Jo", "email": "invalid-email"}' http://localhost:${PORT}/users`);
});
Errors
Common errors & fixes
InputValidationError: Request validation failed
An incoming HTTP request body, query parameters, path parameters, or headers do not conform to the defined OpenAPI schema.
fixExamine the `err.errors` array in the `InputValidationError` object within your error handling middleware to identify specific validation failures. Adjust the client request or OpenAPI schema accordingly.
Cannot find module 'uri-js'
The `uri-js` package, a required peer dependency for OpenAPI schema validation, is not installed in the project.
fixInstall the missing peer dependency: `npm install uri-js`.
Error: Failed to load OpenAPI definition from ...
The `init` or `initAsync` function was called with an incorrect or inaccessible path to the OpenAPI definition file, or the file itself is malformed/invalid.
fixVerify that the `pathToSwaggerFile` argument points to a valid, readable YAML or JSON OpenAPI specification file. Check file permissions and ensure the file content is syntactically correct.
Route handler not validating requests as expected.
The `validate()` middleware is not correctly matching the incoming request path to a defined path in the OpenAPI specification, potentially due to dynamic path parameters or middleware order.
fixEnsure `req.route.path` (for Express) is correctly set by using `validator.validate()` within specific route definitions, rather than globally. For dynamic paths, ensure the OpenAPI path template matches the framework's route definition. Upgrading to `>=3.2.6` can fix issues with empty path parameters for child resources.
Audit
Dependencies
uri-jsrequiredRequired for URI validation within OpenAPI schemas, specified as a peer dependency.