{"id":17626,"library":"express-oas-validator","title":"Express OpenAPI Validator","description":"express-oas-validator is an Express.js middleware library designed for validating API requests and responses against an OpenAPI Specification (OAS) definition. The library, currently at stable version 3.0.1, provides two core functionalities: `validateRequest` for incoming request validation (body, headers, path, query parameters) and `validateResponse` for outgoing response payload validation. It differentiates itself by offering both request and response validation within the same middleware, unlike some alternatives that focus solely on requests. The library's `init` function allows developers to create multiple validator instances for different OpenAPI definitions within a single application. Recent updates, including v3.0.1, have added full TypeScript support, enhancing developer experience. While the release cadence is not strictly regular, major versions have introduced significant improvements and new features.","status":"active","version":"3.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/BRIKEV/express-oas-validator","tags":["javascript","openapi","express","middleware","validator","swagger"],"install":[{"cmd":"npm install express-oas-validator","lang":"bash","label":"npm"},{"cmd":"yarn add express-oas-validator","lang":"bash","label":"yarn"},{"cmd":"pnpm add express-oas-validator","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Recommended for parsing request bodies to enable proper request body validation by the middleware.","package":"body-parser","optional":false}],"imports":[{"note":"The 'init' function is the primary export used to create a validator instance. While CommonJS 'require' syntax works, ESM 'import' is standard for new projects, especially with TypeScript support since v3.0.1.","wrong":"const init = require('express-oas-validator').init;","symbol":"init","correct":"import { init } from 'express-oas-validator';"},{"note":"validateRequest is a function returned by the 'init' factory function, not a direct export from the package. It acts as an Express middleware for request validation. Do not attempt to import it directly.","symbol":"validateRequest","correct":"const { validateRequest } = init(swaggerDefinition);"},{"note":"validateResponse is a function returned by the 'init' factory function, not a direct export from the package. It is used to validate response payloads. Do not attempt to import it directly.","symbol":"validateResponse","correct":"const { validateResponse } = init(swaggerDefinition);"}],"quickstart":{"code":"import express from 'express';\nimport bodyParser from 'body-parser';\nimport { init } from 'express-oas-validator';\n\n// Placeholder for your OpenAPI definition\nconst swaggerDefinition = {\n  openapi: '3.0.0',\n  info: { title: 'Example API', version: '1.0.0' },\n  paths: {\n    '/api/v1/songs': {\n      post: {\n        requestBody: {\n          required: true,\n          content: {\n            'application/json': {\n              schema: { type: 'object', properties: { title: { type: 'string' } }, required: ['title'] }\n            }\n          }\n        },\n        responses: { '200': { description: 'Song saved' } }\n      }\n    },\n    '/api/v1/name': {\n      post: {\n        responses: { '200': { description: 'Hello World response', content: { 'text/plain': { schema: { type: 'string' } } } } }\n      }\n    }\n  }\n};\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\n// Ensure body-parser is configured for request body validation\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(bodyParser.json());\n\nconst { validateRequest, validateResponse } = init(swaggerDefinition);\n\n// Middleware validator for requests\napp.post('/api/v1/songs', validateRequest(), (req, res) => {\n  console.log('Received song:', req.body);\n  res.send('You saved a song!');\n});\n\n// Response validator\napp.post('/api/v1/name', (req, res, next) => {\n  try {\n    // Example: validate a string response for status 200\n    validateResponse('Hello World!', req, 200);\n    return res.send('Hello World!');\n  } catch (error) {\n    // Ensure error handling for response validation failures\n    return next(error);\n  }\n});\n\n// Express default error handler for validation errors\napp.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {\n  console.error('Validation Error:', err);\n  if (err.status) {\n    return res.status(err.status).json(err);\n  }\n  res.status(500).json({ status: 500, message: 'Internal Server Error', originalError: err.message });\n});\n\napp.listen(PORT, () => {\n  console.log(`Server listening on port ${PORT}`);\n});\n","lang":"typescript","description":"This example demonstrates how to set up `express-oas-validator` with an Express application, using `init` to get `validateRequest` and `validateResponse` middleware. It shows basic request body validation and response payload validation for two different routes against a simple OpenAPI definition, including error handling."},"warnings":[{"fix":"Update your code to use `validateRequest` and `validateResponse` instead of `validate`. Ensure you destructure them from the object returned by `init()`.","message":"In version 2.0.0, the primary validation methods were renamed. The single `validate` method was split and renamed to `validateRequest` (for input validation) and `validateResponse` (for output validation).","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Review the full changelog on GitHub (`v2.0.2...v3.0.0`) when upgrading from v2 to v3 to understand all necessary code modifications. Updating is strongly recommended due to performance improvements.","message":"Version 3.0.0 introduced significant changes, including unspecified breaking changes, which may require adjustments to your existing implementation. It also fixed an 'important performance issue'.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Always install and configure `body-parser` middleware in your Express application before `express-oas-validator` for routes that require body validation (e.g., `app.use(bodyParser.json());`).","message":"Although an older changelog (v1.0.1) mentioned 'Remove deprecated body-parser', the library's current documentation (v3.x) still explicitly recommends using `body-parser` for request body validation. Failing to include `body-parser` middleware for parsing request bodies (e.g., JSON) will lead to validation errors as the `req.body` object will be empty.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Rename `validate()` calls to `validateRequest()` for incoming requests and `validateResponse()` for outgoing responses. Remember these are obtained from the `init()` function: `const { validateRequest, validateResponse } = init(swaggerDefinition);`","cause":"Attempting to use the old `validate` method name from versions prior to 2.0.0, after upgrading to version 2.0.0 or higher.","error":"TypeError: validate is not a function"},{"fix":"Ensure you pass your OpenAPI/Swagger definition object to the `init` function: `init(yourSwaggerDefinitionObject)`.","cause":"The `init` function was called without providing a valid OpenAPI definition object as its first argument.","error":"Error: \"openApiDef\" parameter is required"},{"fix":"Check the client-side request payload to ensure it matches the schema defined in your OpenAPI documentation for that endpoint and verify `body-parser` is correctly configured.","cause":"The incoming request body does not conform to the OpenAPI schema defined for the endpoint, specifically missing a required property.","error":"ValidationError: request.body should have required property 'propertyName'"},{"fix":"Install `body-parser` via npm (`npm install body-parser`) and import it in your application file (`import bodyParser from 'body-parser';` or `const bodyParser = require('body-parser');`).","cause":"`body-parser` middleware is used in an Express application but has not been imported or installed.","error":"ReferenceError: bodyParser is not defined"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}