{"id":17121,"library":"openapi-validator-middleware","title":"OpenAPI Validator Middleware","description":"This package, `openapi-validator-middleware`, provides robust input validation for HTTP requests within Node.js frameworks such as Express, Koa, and Fastify. It leverages your existing OpenAPI (formerly Swagger) 2.0 or 3.0 definition files to automatically validate request bodies, headers, path parameters, and query parameters, using the powerful AJV library under the hood. The current stable version is 3.2.6, with the last significant update in February 2022. This suggests a maintenance-focused release cadence rather than active feature development, as over four years have passed since its last update. A key differentiator is its multi-framework support and its reliance on standardized OpenAPI definitions for validation logic, offering a consistent approach to API input schema enforcement. It was notably renamed from `express-ajv-swagger-validation` starting with version 2.0.0, which was a breaking change primarily affecting package naming and import paths for existing users.","status":"maintenance","version":"3.2.6","language":"javascript","source_language":"en","source_url":"https://github.com/PayU/openapi-validator-middleware","tags":["javascript","ajv","express","swagger","openapi","open api","input validation","request","validation","typescript"],"install":[{"cmd":"npm install openapi-validator-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add openapi-validator-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add openapi-validator-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for URI validation within OpenAPI schemas, specified as a peer dependency.","package":"uri-js","optional":false}],"imports":[{"note":"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.","wrong":"import { init, validate } from 'openapi-validator-middleware';","symbol":"validator object (default export)","correct":"import validator from 'openapi-validator-middleware';"},{"note":"This is the standard CommonJS import pattern. Functions and error class are accessed as properties of the `validator` object.","wrong":"const { validate } = require('openapi-validator-middleware');","symbol":"validator (CommonJS require)","correct":"const validator = require('openapi-validator-middleware');"},{"note":"The InputValidationError class is a property of the default-exported validator object, and should be destructured from it or accessed directly via `validator.InputValidationError`.","wrong":"import { InputValidationError } from 'openapi-validator-middleware';","symbol":"InputValidationError","correct":"import validator from 'openapi-validator-middleware'; const { InputValidationError } = validator;"}],"quickstart":{"code":"import express from 'express';\nimport path from 'path';\nimport validator from 'openapi-validator-middleware';\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\n// Dummy OpenAPI spec for demonstration\nconst swaggerSpecPath = path.resolve('./swagger.yaml');\n// In a real app, this would be a real file:\n// fs.writeFileSync(swaggerSpecPath, `\n// openapi: 3.0.0\n// info:\n//   title: Test API\n//   version: 1.0.0\n// paths:\n//   /users:\n//     post:\n//       requestBody:\n//         required: true\n//         content:\n//           application/json:\n//             schema:\n//               type: object\n//               properties:\n//                 name:\n//                   type: string\n//                 email:\n//                   type: string\n//                   format: email\n//               required:\n//                 - name\n//                 - email\n//       responses:\n//         '200':\n//           description: User created\n// `);\n\n// In a real application, ensure the OpenAPI file exists.\n// For this example, we'll initialize without reading a file directly\n// to focus on the middleware usage, but you'd normally point to your spec.\n// For simplicity, we'll manually define a schema here.\n// In a real scenario, you would initialize with a path to your spec file:\n// validator.init(swaggerSpecPath, { source: 'fs' });\n\n// Simulate initialization with an in-memory spec if no file is present\n// For a real setup, provide a path to your YAML/JSON OpenAPI spec.\nconst inMemorySpec = {\n  openapi: '3.0.0',\n  info: { title: 'Test API', version: '1.0.0' },\n  paths: {\n    '/users': {\n      post: {\n        requestBody: {\n          required: true,\n          content: {\n            'application/json': {\n              schema: {\n                type: 'object',\n                properties: {\n                  name: { type: 'string' },\n                  email: { type: 'string', format: 'email' }\n                },\n                required: ['name', 'email']\n              }\n            }\n          }\n        },\n        responses: { '200': { description: 'User created' } }\n      }\n    }\n  }\n};\n\n// NOTE: In a real scenario, you'd call validator.init(pathToSwaggerFile)\n// We simulate by directly setting the internal schema for demonstration.\n// This part is for demonstration only, the library expects a file path.\nconsole.warn('Initializing openapi-validator-middleware without a physical file for demo. Provide a path to your spec in a real app.');\n// A more realistic init would be:\n// try {\n//   await validator.initAsync(swaggerSpecPath);\n// } catch (error) {\n//   console.error('Failed to initialize validator:', error.message);\n//   process.exit(1);\n// }\n\n// This requires manually mocking the internal state, not directly possible via public API.\n// So, for a runnable quickstart, we need an actual OpenAPI file.\n// Let's create a minimal one for the example.\n\nconst fs = require('fs');\nconst swaggerContent = `\nopenapi: 3.0.0\ninfo:\n  title: Test API\n  version: 1.0.0\npaths:\n  /users:\n    post:\n      summary: Create a new user\n      requestBody:\n        required: true\n        content:\n          application/json:\n            schema:\n              type: object\n              properties:\n                name:\n                  type: string\n                  minLength: 3\n                email:\n                  type: string\n                  format: email\n              required:\n                - name\n                - email\n      responses:\n        '201':\n          description: User created successfully\n        '400':\n          description: Invalid input\n`;\nfs.writeFileSync(swaggerSpecPath, swaggerContent);\n\nvalidator.init(swaggerSpecPath);\n\napp.use(express.json()); // Body parser middleware\n\napp.post('/users', validator.validate(), (req, res) => {\n  // If validation passes, process the request\n  res.status(201).json({ message: 'User created', data: req.body });\n});\n\n// Error handling middleware for validation errors\napp.use((err, req, res, next) => {\n  if (err instanceof validator.InputValidationError) {\n    return res.status(400).json({ \n      message: 'Validation Error', \n      errors: err.errors,\n      validationContext: err.validationContext \n    });\n  }\n  next(err);\n});\n\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log(`Test with: curl -X POST -H \"Content-Type: application/json\" -d '{\"name\": \"John Doe\", \"email\": \"john@example.com\"}' http://localhost:${PORT}/users`);\n  console.log(`Test validation failure with: curl -X POST -H \"Content-Type: application/json\" -d '{\"name\": \"Jo\", \"email\": \"invalid-email\"}' http://localhost:${PORT}/users`);\n});","lang":"typescript","description":"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`."},"warnings":[{"fix":"Update `package.json` dependencies to `openapi-validator-middleware` and change `require` or `import` statements accordingly. For example, `require('express-ajv-swagger-validation')` becomes `require('openapi-validator-middleware')`.","message":"The package was renamed from `express-ajv-swagger-validation` to `openapi-validator-middleware` in version 2.0.0. Existing users must update package names and import paths.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Prefer `await validator.initAsync(pathToSwaggerFile)` over `validator.init(pathToSwaggerFile)` to prevent blocking and handle potential file loading errors gracefully.","message":"The initialization functions come in synchronous (`init`) and asynchronous (`initAsync`) variants. `init` will block the event loop, while `initAsync` returns a Promise. For robust application startup, especially when loading potentially large OpenAPI definition files, `initAsync` is recommended.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Integrate a dedicated multipart parsing middleware (e.g., `express-formidable`, `multer`) prior to `openapi-validator-middleware.validate()` in your Express/Koa/Fastify route chain.","message":"Validation of `multipart/form-data` requests has specific considerations. The middleware typically processes JSON or URL-encoded bodies. For file uploads or complex multipart data, additional parsing middleware (e.g., `multer` for Express) is required *before* `openapi-validator-middleware` to make the data available for validation.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Upgrade to the latest stable version (`3.2.6` or newer) to ensure all known security patches are applied.","message":"Multiple security vulnerabilities have been addressed in various versions, including fixes for vulnerable packages in dependencies and general security enhancements. It is crucial to stay updated to mitigate known risks.","severity":"security","affected_versions":"<3.2.3"},{"fix":"Ensure `uri-js` is installed in your project: `npm install uri-js` or `yarn add uri-js`.","message":"The package lists `uri-js` as a peer dependency. If `uri-js` is not installed in your project, you may encounter errors related to URI validation or missing modules at runtime.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Examine 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.","cause":"An incoming HTTP request body, query parameters, path parameters, or headers do not conform to the defined OpenAPI schema.","error":"InputValidationError: Request validation failed"},{"fix":"Install the missing peer dependency: `npm install uri-js`.","cause":"The `uri-js` package, a required peer dependency for OpenAPI schema validation, is not installed in the project.","error":"Cannot find module 'uri-js'"},{"fix":"Verify 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.","cause":"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.","error":"Error: Failed to load OpenAPI definition from ..."},{"fix":"Ensure `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.","cause":"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.","error":"Route handler not validating requests as expected."}],"ecosystem":"npm","meta_description":null}