Koa2 Swagger UI Middleware

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

koa2-swagger-ui provides a middleware for Koa v2 applications, enabling developers to easily host Swagger UI at a specified route. It integrates directly into the Koa request-response cycle, allowing for API documentation to be served alongside the application. The package is currently at version 5.12.0 and maintains an active release cadence, with multiple updates per year to bump internal Swagger UI versions and add features. Key differentiators include its tight integration with the Koa ecosystem, offering simple configuration for routes, spec loading (from URL or inline object), and customization options for the UI's appearance, such as custom CSS and CDN URLs for Swagger assets. It also supports loading OpenAPI specifications from YAML files via `yamljs`.

error Error: ENOENT: no such file or directory, stat './openapi.yaml'
cause The OpenAPI specification file (e.g., `openapi.yaml`) specified in the `spec` option was not found at the given path.
fix
Ensure the path to your spec file is correct and absolute, or that the file exists relative to your current working directory when the application starts. Use path.resolve(__dirname, 'your-spec.yaml') for clarity.
error TypeError: koaSwagger is not a function
cause Incorrect import syntax (e.g., using `require` with a named export, or attempting a default import when none exists) or missing package installation.
fix
Ensure koa2-swagger-ui is installed and use import { koaSwagger } from 'koa2-swagger-ui'; for ESM, or const { koaSwagger } = require('koa2-swagger-ui'); for CommonJS if compatible.
error The `url` or `spec` option must be provided for Swagger UI configuration.
cause The `swaggerOptions` object passed to `koaSwagger` is missing either the `url` property pointing to a remote OpenAPI spec, or the `spec` property containing the OpenAPI definition object directly.
fix
Ensure your koaSwagger configuration includes swaggerOptions: { url: 'your-spec-url.json' } or swaggerOptions: { spec: yourSpecObject }.
error TypeError: Cannot read properties of undefined (reading 'routes')
cause Incorrectly importing or initializing `koa-router` when attempting to use its methods.
fix
Ensure you have koa-router installed (npm install koa-router) and correctly imported import Router from 'koa-router'; then initialized const router = new Router(); before using it with app.use(router.routes()).
breaking Since v5.10.0, `@types/koa` has been moved to a peer dependency. TypeScript users will need to explicitly install `@types/koa` if not already present in their project to avoid type errors.
fix Run `npm install --save-dev @types/koa` or `yarn add -D @types/koa`.
gotcha The underlying Swagger UI library is frequently updated within `koa2-swagger-ui` releases. While this brings new features and bug fixes, it can occasionally introduce subtle changes in UI behavior or options. Review Swagger UI's own changelog for specific changes.
fix Consult the `koa2-swagger-ui` release notes and the upstream Swagger UI documentation for changes in each major/minor version bump.
gotcha The `koaSwagger` function accepts an options object, which includes `swaggerOptions` (passed directly to SwaggerUI) and other `koa2-swagger-ui` specific options like `routePrefix`, `specPrefix`, `customCSS`, and `swaggerCdnUrl`. It's common to confuse where certain options should be placed.
fix Refer to the `koa2-swagger-ui` documentation for the top-level options, and the official Swagger UI documentation for options nested under `swaggerOptions`.
gotcha The `swaggerVersion` option within `swaggerOptions` is internally populated from the package's `package.json` and is not intended for manual configuration. Setting it explicitly will likely have no effect or could lead to unexpected behavior.
fix Avoid setting `swaggerVersion` manually. The middleware automatically uses the bundled Swagger UI version.
npm install koa2-swagger-ui
yarn add koa2-swagger-ui
pnpm add koa2-swagger-ui

Demonstrates how to integrate `koa2-swagger-ui` into a Koa application using `koa-router` and load an OpenAPI specification from a local YAML file, serving the interactive documentation.

import Koa from 'koa';
import Router from 'koa-router';
import { koaSwagger } from 'koa2-swagger-ui';
import yamljs from 'yamljs';
import fs from 'node:fs';
import path from 'node:path';

const app = new Koa();
const router = new Router();

// Define an OpenAPI spec (e.g., in YAML)
const openApiSpecPath = path.resolve(__dirname, 'openapi.yaml');
// For a real app, you'd generate this or load it from a stable source.
// Here we create a dummy one if it doesn't exist for the example to run.
if (!fs.existsSync(openApiSpecPath)) {
  fs.writeFileSync(openApiSpecPath, `
openapi: 3.0.0
info:
  title: Koa2 Swagger UI Example API
  version: 1.0.0
paths:
  /hello:
    get:
      summary: Greets the world
      responses:
        '200':
          description: A simple greeting
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Hello, Koa!
`);
}
const spec = yamljs.load(openApiSpecPath);

// Serve the Swagger UI
router.get('/docs', koaSwagger({
  routePrefix: false, // Disables the default /docs prefix for the UI
  swaggerOptions: {
    spec, // Provide the spec object directly
    // Alternatively, for a remote spec: url: 'http://petstore.swagger.io/v2/swagger.json',
  },
  title: 'Koa API Documentation',
  hideTopbar: true,
}));

// Add a simple API route for demonstration
router.get('/hello', (ctx) => {
  ctx.body = { message: 'Hello, Koa!' };
});

app.use(router.routes()).use(router.allowedMethods());

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log(`API Docs available at http://localhost:${PORT}/docs`);
  console.log('Use CTRL+C to stop the server.');
});

// To run this:
// 1. npm install koa koa-router koa2-swagger-ui yamljs @types/koa @types/koa-router @types/yamljs typescript ts-node
// 2. Add "type": "module" to package.json
// 3. npx ts-node your-file.ts
// Then open http://localhost:3000/docs