Registry / web-framework / swagger2-koa

swagger2-koa

JSON →
library5.1.0jsnpmunverified

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-koa
INSTALL
IMPORT
SIG · SWAGGER2-KOA
S
swagger2-koa
web-frameworkjavascriptv5.1.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

router
import { router } from 'swagger2-koa';
const { router } = require('swagger2-koa');
Package is ESM-only since v5.0.0. Use named import for the `router` factory function.
validate
import { validate } from 'swagger2-koa';
const { validate } = require('swagger2-koa');
Package is ESM-only since v5.0.0. Use named import for the `validate` middleware factory.
Router
import { Router } from 'swagger2-koa';
Use named import for the `Router` type if using TypeScript to define your router instance.

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'); });
Debug
Known issues
breakingVersion 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.
affects: >=5.0.0
breakingVersion 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.
affects: >=5.0.0
breakingThe `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.
affects: >=4.0.0
gotchaThe `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.
affects: >=1.0.0
gotchaIf 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.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: (0 , swagger2_koa_1.router) is not a function
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: ./*swagger.yml does not conform to the Swagger 2.0 schema
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.
HTTP 400 Bad Request: Request body does not validate
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.
HTTP 500 Internal Server Error: Response body does not validate
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.
Upgrade
Version history
5.1.0latest on npm
Audit
Dependencies
swagger2requiredRequired to load and parse Swagger 2.0 documents.
Agent activity
13 hits · last 30 days
node
12
OpenAI (training)
1
Resources
swagger2-koa — npm install swagger2-koa · libregistry