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.
npm install swagger2-koaVerified import paths — ran on the pinned version, not inferred.
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.
Migrate your project to use ES modules (`import`/`export`) or stick to an earlier version if CommonJS is required.
Ensure your environment is running Node.js version 22 or higher.
If you require Swagger UI, integrate a separate `swagger-ui-koa` or similar package into your application.
Always apply a body parsing middleware (e.g., `koa-bodyparser`, `koa-body`) before `swagger2-koa`'s `validate` middleware. The `router` utility handles this automatically.
Ensure all intended API paths are correctly defined within your Swagger 2.0 document.
Ensure your project is configured for ES modules and use `import { router } from 'swagger2-koa';`.Validate your `swagger.yml` or `swagger.json` file using an external tool or schema validator before loading it.
Review the detailed errors provided in the response body and adjust the client's request payload to match the Swagger schema.
Examine the detailed errors in the response body and modify your Koa handler to return a response payload that matches the expected Swagger schema.