Koa 2 Middleware for Swagger 2.0 Validation
raw JSON →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.
Common errors
error TypeError: (0 , swagger2_koa_1.router) is not a function ↓
import { router } from 'swagger2-koa';. error Error: ./*swagger.yml does not conform to the Swagger 2.0 schema ↓
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 ↓
error HTTP 500 Internal Server Error: Response body does not validate ↓
Warnings
breaking Version 5.0.0 introduced a breaking change by becoming an ESM-only package. CommonJS `require()` statements will no longer work. ↓
breaking Version 5.0.0 raised the minimum Node.js version requirement to `Node.js >= 22`. ↓
breaking The `swagger-ui` feature was removed in version 4.0.0 due to security concerns. ↓
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. ↓
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. ↓
Install
npm install swagger2-koa yarn add swagger2-koa pnpm add swagger2-koa Imports
- router wrong
const { router } = require('swagger2-koa');correctimport { router } from 'swagger2-koa'; - validate wrong
const { validate } = require('swagger2-koa');correctimport { validate } from 'swagger2-koa'; - Router
import { Router } from 'swagger2-koa';
Quickstart
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');
});