{"id":17971,"library":"swagger2-koa","title":"Koa 2 Middleware for Swagger 2.0 Validation","description":"swagger2-koa is a Koa 2 middleware package designed for loading, parsing, and validating incoming HTTP requests and outgoing responses against a Swagger 2.0 document. As of version 5.1.0, it targets Node.js version 22 or higher and is an ESM-only package. The library offers two primary modes of operation: a comprehensive `router` utility that sets up a full Koa server with pre-configured middleware (including `@koa/cors`, `@koa/router`, and `koa-bodyparser`), or a standalone `validate` middleware for integration into existing Koa applications. It strictly enforces schema validation, returning HTTP 400 for invalid requests and HTTP 500 for invalid responses, providing detailed validation errors. The release cadence is driven by dependency updates and major refactors, such as the recent transition to ESM. Its key differentiator lies in its specific focus on Koa 2 and Swagger 2.0, providing robust API contract enforcement.","status":"active","version":"5.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/carlansley/swagger2-koa","tags":["javascript","swagger","swagger2","typescript","koa","koa2"],"install":[{"cmd":"npm install swagger2-koa","lang":"bash","label":"npm"},{"cmd":"yarn add swagger2-koa","lang":"bash","label":"yarn"},{"cmd":"pnpm add swagger2-koa","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required to load and parse Swagger 2.0 documents.","package":"swagger2","optional":false}],"imports":[{"note":"Package is ESM-only since v5.0.0. Use named import for the `router` factory function.","wrong":"const { router } = require('swagger2-koa');","symbol":"router","correct":"import { router } from 'swagger2-koa';"},{"note":"Package is ESM-only since v5.0.0. Use named import for the `validate` middleware factory.","wrong":"const { validate } = require('swagger2-koa');","symbol":"validate","correct":"import { validate } from 'swagger2-koa';"},{"note":"Use named import for the `Router` type if using TypeScript to define your router instance.","symbol":"Router","correct":"import { Router } from 'swagger2-koa';"}],"quickstart":{"code":"import * as swagger from 'swagger2';\nimport { router as swaggerRouter, Router } from 'swagger2-koa';\nimport path from 'path';\nimport fs from 'fs';\n\nconst documentPath = path.resolve(__dirname, './swagger.yml');\n// Create a dummy swagger.yml for demonstration purposes if it doesn't exist\nif (!fs.existsSync(documentPath)) {\n  fs.writeFileSync(documentPath, `\nswagger: '2.0'\ninfo:\n  title: Test API\n  version: '1.0.0'\npaths:\n  /ping:\n    get:\n      summary: Ping endpoint\n      operationId: ping\n      responses:\n        '200':\n          description: Success\n          schema:\n            type: object\n            properties:\n              serverTime:\n                type: string\n                format: date-time\n  `);\n}\n\n// In a real application, you'd load your actual swagger.yml\nconst document = swagger.loadDocumentSync(documentPath);\n\n// Ensure the document is valid (optional, but good practice)\nif (!swagger.validateDocument(document)) {\n  throw Error(`${documentPath} does not conform to the Swagger 2.0 schema`);\n}\n\nconst router: Router = swaggerRouter(document);\n\nrouter.get('/ping', async (context) => {\n  context.status = 200;\n  context.body = {\n    serverTime: new Date().toISOString(),\n  };\n});\n\nconst port = process.env.PORT ?? 3000;\nrouter.app().listen(port, () => {\n  console.log(`Server running on http://localhost:${port}`);\n  console.log('Try: curl http://localhost:3000/ping');\n});","lang":"typescript","description":"Demonstrates setting up a Koa server with `swagger2-koa`'s `router` utility, which automatically configures validation, CORS, and body parsing, then defining a simple API endpoint."},"warnings":[{"fix":"Migrate your project to use ES modules (`import`/`export`) or stick to an earlier version if CommonJS is required.","message":"Version 5.0.0 introduced a breaking change by becoming an ESM-only package. CommonJS `require()` statements will no longer work.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Ensure your environment is running Node.js version 22 or higher.","message":"Version 5.0.0 raised the minimum Node.js version requirement to `Node.js >= 22`.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"If you require Swagger UI, integrate a separate `swagger-ui-koa` or similar package into your application.","message":"The `swagger-ui` feature was removed in version 4.0.0 due to security concerns.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Always apply a body parsing middleware (e.g., `koa-bodyparser`, `koa-body`) before `swagger2-koa`'s `validate` middleware. The `router` utility handles this automatically.","message":"The `validate` middleware expects `context.body` to contain the request body as an object. If no body parser is used before `validate`, validation will fail or behave unexpectedly.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure all intended API paths are correctly defined within your Swagger 2.0 document.","message":"If a request path is not defined in the provided Swagger document, `swagger2-koa` will return an HTTP 404 'Not Found' error, preventing subsequent middleware from being processed.","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":"Ensure your project is configured for ES modules and use `import { router } from 'swagger2-koa';`.","cause":"Attempting to use `require()` or incorrect import syntax for an ESM-only package.","error":"TypeError: (0 , swagger2_koa_1.router) is not a function"},{"fix":"Validate your `swagger.yml` or `swagger.json` file using an external tool or schema validator before loading it.","cause":"The loaded Swagger document is syntactically or structurally invalid according to the Swagger 2.0 specification.","error":"Error: ./*swagger.yml does not conform to the Swagger 2.0 schema"},{"fix":"Review the detailed errors provided in the response body and adjust the client's request payload to match the Swagger schema.","cause":"The incoming request payload does not conform to the schema defined in your Swagger 2.0 document for the respective endpoint.","error":"HTTP 400 Bad Request: Request body does not validate"},{"fix":"Examine the detailed errors in the response body and modify your Koa handler to return a response payload that matches the expected Swagger schema.","cause":"The response being sent from your Koa handler does not conform to the `responses` schema defined in your Swagger 2.0 document for the specific status code.","error":"HTTP 500 Internal Server Error: Response body does not validate"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}