{"id":17770,"library":"koa2-swagger-ui","title":"Koa2 Swagger UI Middleware","description":"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`.","status":"active","version":"5.12.0","language":"javascript","source_language":"en","source_url":"https://github.com/scttcper/koa2-swagger-ui","tags":["javascript","swagger","docs","swagger-ui","koa","koa2","middleware","typescript"],"install":[{"cmd":"npm install koa2-swagger-ui","lang":"bash","label":"npm"},{"cmd":"yarn add koa2-swagger-ui","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa2-swagger-ui","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency required for TypeScript users to correctly type Koa applications when using this middleware.","package":"@types/koa","optional":true},{"reason":"Implicit runtime dependency as this is a Koa middleware. Koa must be installed in your project.","package":"koa","optional":false},{"reason":"Optional dependency for more complex routing setups, often used in conjunction with this middleware, as shown in examples.","package":"koa-router","optional":true},{"reason":"Optional dependency required for loading OpenAPI specifications from YAML files.","package":"yamljs","optional":true}],"imports":[{"note":"The package primarily uses named exports. While CommonJS `require` can be used, the modern `import` syntax is preferred for ESM projects.","wrong":"const koaSwagger = require('koa2-swagger-ui');","symbol":"koaSwagger","correct":"import { koaSwagger } from 'koa2-swagger-ui';"},{"note":"This is a TypeScript type interface for configuring the middleware. Use it for strong typing when defining options.","symbol":"KoaSwaggerUiOptions","correct":"import { KoaSwaggerUiOptions } from 'koa2-swagger-ui';"},{"note":"This is an import for `koa-router`, an optional but common dependency when defining routes for `koa2-swagger-ui`.","wrong":"const Router = require('koa-router');","symbol":"Router","correct":"import Router from 'koa-router';"}],"quickstart":{"code":"import Koa from 'koa';\nimport Router from 'koa-router';\nimport { koaSwagger } from 'koa2-swagger-ui';\nimport yamljs from 'yamljs';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nconst app = new Koa();\nconst router = new Router();\n\n// Define an OpenAPI spec (e.g., in YAML)\nconst openApiSpecPath = path.resolve(__dirname, 'openapi.yaml');\n// For a real app, you'd generate this or load it from a stable source.\n// Here we create a dummy one if it doesn't exist for the example to run.\nif (!fs.existsSync(openApiSpecPath)) {\n  fs.writeFileSync(openApiSpecPath, `\nopenapi: 3.0.0\ninfo:\n  title: Koa2 Swagger UI Example API\n  version: 1.0.0\npaths:\n  /hello:\n    get:\n      summary: Greets the world\n      responses:\n        '200':\n          description: A simple greeting\n          content:\n            application/json:\n              schema:\n                type: object\n                properties:\n                  message:\n                    type: string\n                    example: Hello, Koa!\n`);\n}\nconst spec = yamljs.load(openApiSpecPath);\n\n// Serve the Swagger UI\nrouter.get('/docs', koaSwagger({\n  routePrefix: false, // Disables the default /docs prefix for the UI\n  swaggerOptions: {\n    spec, // Provide the spec object directly\n    // Alternatively, for a remote spec: url: 'http://petstore.swagger.io/v2/swagger.json',\n  },\n  title: 'Koa API Documentation',\n  hideTopbar: true,\n}));\n\n// Add a simple API route for demonstration\nrouter.get('/hello', (ctx) => {\n  ctx.body = { message: 'Hello, Koa!' };\n});\n\napp.use(router.routes()).use(router.allowedMethods());\n\nconst PORT = 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log(`API Docs available at http://localhost:${PORT}/docs`);\n  console.log('Use CTRL+C to stop the server.');\n});\n\n// To run this:\n// 1. npm install koa koa-router koa2-swagger-ui yamljs @types/koa @types/koa-router @types/yamljs typescript ts-node\n// 2. Add \"type\": \"module\" to package.json\n// 3. npx ts-node your-file.ts\n// Then open http://localhost:3000/docs","lang":"typescript","description":"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."},"warnings":[{"fix":"Run `npm install --save-dev @types/koa` or `yarn add -D @types/koa`.","message":"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.","severity":"breaking","affected_versions":">=5.10.0"},{"fix":"Consult the `koa2-swagger-ui` release notes and the upstream Swagger UI documentation for changes in each major/minor version bump.","message":"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.","severity":"gotcha","affected_versions":">=5.0.0"},{"fix":"Refer to the `koa2-swagger-ui` documentation for the top-level options, and the official Swagger UI documentation for options nested under `swaggerOptions`.","message":"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.","severity":"gotcha","affected_versions":"*"},{"fix":"Avoid setting `swaggerVersion` manually. The middleware automatically uses the bundled Swagger UI version.","message":"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.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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.","cause":"The OpenAPI specification file (e.g., `openapi.yaml`) specified in the `spec` option was not found at the given path.","error":"Error: ENOENT: no such file or directory, stat './openapi.yaml'"},{"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.","cause":"Incorrect import syntax (e.g., using `require` with a named export, or attempting a default import when none exists) or missing package installation.","error":"TypeError: koaSwagger is not a function"},{"fix":"Ensure your `koaSwagger` configuration includes `swaggerOptions: { url: 'your-spec-url.json' }` or `swaggerOptions: { spec: yourSpecObject }`.","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.","error":"The `url` or `spec` option must be provided for Swagger UI configuration."},{"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())`.","cause":"Incorrectly importing or initializing `koa-router` when attempting to use its methods.","error":"TypeError: Cannot read properties of undefined (reading 'routes')"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}