Koa 2 Middleware for Swagger 2.0 Validation

raw JSON →
5.1.0 verified Thu Apr 23 auth: no javascript

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.

error TypeError: (0 , swagger2_koa_1.router) is not a function
cause Attempting to use `require()` or incorrect import syntax for an ESM-only package.
fix
Ensure your project is configured for ES modules and use import { router } from 'swagger2-koa';.
error Error: ./*swagger.yml does not conform to the Swagger 2.0 schema
cause The loaded Swagger document is syntactically or structurally invalid according to the Swagger 2.0 specification.
fix
Validate your swagger.yml or swagger.json file using an external tool or schema validator before loading it.
error HTTP 400 Bad Request: Request body does not validate
cause The incoming request payload does not conform to the schema defined in your Swagger 2.0 document for the respective endpoint.
fix
Review the detailed errors provided in the response body and adjust the client's request payload to match the Swagger schema.
error HTTP 500 Internal Server Error: Response body does not validate
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.
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.
breaking Version 5.0.0 introduced a breaking change by becoming an ESM-only package. CommonJS `require()` statements will no longer work.
fix Migrate your project to use ES modules (`import`/`export`) or stick to an earlier version if CommonJS is required.
breaking Version 5.0.0 raised the minimum Node.js version requirement to `Node.js >= 22`.
fix Ensure your environment is running Node.js version 22 or higher.
breaking The `swagger-ui` feature was removed in version 4.0.0 due to security concerns.
fix If you require Swagger UI, integrate a separate `swagger-ui-koa` or similar package into your application.
gotcha 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.
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.
gotcha 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.
fix Ensure all intended API paths are correctly defined within your Swagger 2.0 document.
npm install swagger2-koa
yarn add swagger2-koa
pnpm add swagger2-koa

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.

import * as swagger from 'swagger2';
import { router as swaggerRouter, Router } from 'swagger2-koa';
import path from 'path';
import fs from 'fs';

const documentPath = path.resolve(__dirname, './swagger.yml');
// Create a dummy swagger.yml for demonstration purposes if it doesn't exist
if (!fs.existsSync(documentPath)) {
  fs.writeFileSync(documentPath, `
swagger: '2.0'
info:
  title: Test API
  version: '1.0.0'
paths:
  /ping:
    get:
      summary: Ping endpoint
      operationId: ping
      responses:
        '200':
          description: Success
          schema:
            type: object
            properties:
              serverTime:
                type: string
                format: date-time
  `);
}

// In a real application, you'd load your actual swagger.yml
const document = swagger.loadDocumentSync(documentPath);

// Ensure the document is valid (optional, but good practice)
if (!swagger.validateDocument(document)) {
  throw Error(`${documentPath} does not conform to the Swagger 2.0 schema`);
}

const router: Router = swaggerRouter(document);

router.get('/ping', async (context) => {
  context.status = 200;
  context.body = {
    serverTime: new Date().toISOString(),
  };
});

const port = process.env.PORT ?? 3000;
router.app().listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
  console.log('Try: curl http://localhost:3000/ping');
});