{"id":13515151,"url":"https://github.com/fastify/fastify-swagger-ui","last_synced_at":"2025-05-15T02:01:58.398Z","repository":{"id":60634803,"uuid":"532896794","full_name":"fastify/fastify-swagger-ui","owner":"fastify","description":"Serve Swagger-UI for Fastify","archived":false,"fork":false,"pushed_at":"2025-05-01T22:46:46.000Z","size":325,"stargazers_count":160,"open_issues_count":6,"forks_count":42,"subscribers_count":12,"default_branch":"main","last_synced_at":"2025-05-01T23:27:25.143Z","etag":null,"topics":["documentation","fastify","fastify-plugin","openapi","swagger"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/@fastify/swagger-ui","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fastify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2022-09-05T12:44:34.000Z","updated_at":"2025-05-01T22:46:42.000Z","dependencies_parsed_at":"2023-12-06T09:29:01.873Z","dependency_job_id":"fb915add-b4a0-4485-b3a1-9d328dbbdbd5","html_url":"https://github.com/fastify/fastify-swagger-ui","commit_stats":{"total_commits":154,"total_committers":36,"mean_commits":4.277777777777778,"dds":0.6103896103896104,"last_synced_commit":"4b7c013274df8557761c72325833e3438848d804"},"previous_names":[],"tags_count":34,"template":false,"template_full_name":"fastify/skeleton","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-swagger-ui","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-swagger-ui/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-swagger-ui/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-swagger-ui/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fastify-swagger-ui/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254259364,"owners_count":22040816,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["documentation","fastify","fastify-plugin","openapi","swagger"],"created_at":"2024-08-01T05:01:06.843Z","updated_at":"2025-05-15T02:01:58.309Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# @fastify/swagger-ui\n\n[![NPM version](https://img.shields.io/npm/v/@fastify/swagger-ui.svg?style=flat)](https://www.npmjs.com/package/@fastify/swagger-ui)\n[![CI](https://github.com/fastify/fastify-swagger-ui/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-swagger-ui/actions/workflows/ci.yml)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nA Fastify plugin for serving [Swagger UI](https://swagger.io/tools/swagger-ui/).\n\n![Demo](https://user-images.githubusercontent.com/52195/228162405-c85ad0d1-900d-442a-b712-7108d98d621f.png)\n\n\u003ca name=\"install\"\u003e\u003c/a\u003e\n## Install\n```\nnpm i @fastify/swagger-ui\n```\n\n### Compatibility\n\n| Plugin version | Fastify version | Swagger Plugin Version |\n| -------------- | --------------- | ---------------------- |\n| `^5.x`         | `^5.x`          | `^9.x`                 |\n| `^2.x`         | `^4.x`          | `^8.x`                 |\n| `^1.x`         | `^4.x`          | `^8.x`                 |\n\n\nPlease note that if a Fastify version is out of support, then so are the corresponding versions of this plugin\nin the table above.\nSee [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details.\n\n\u003ca name=\"usage\"\u003e\u003c/a\u003e\n## Usage\nAdd it with `@fastify/swagger` to your project with `register`, pass it some options, call the `swagger` API, and you are done!\n\n```js\nimport fastify from 'fastify'\n\nconst app = fastify()\n\nawait app.register(import('@fastify/swagger'))\n\nawait app.register(import('@fastify/swagger-ui'), {\n  routePrefix: '/documentation',\n  uiConfig: {\n    docExpansion: 'full',\n    deepLinking: false\n  },\n  uiHooks: {\n    onRequest: function (request, reply, next) { next() },\n    preHandler: function (request, reply, next) { next() }\n  },\n  staticCSP: true,\n  transformStaticCSP: (header) =\u003e header,\n  transformSpecification: (swaggerObject, request, reply) =\u003e { return swaggerObject },\n  transformSpecificationClone: true\n})\n\napp.put('/some-route/:id', {\n  schema: {\n    description: 'post some data',\n    tags: ['user', 'code'],\n    summary: 'qwerty',\n    params: {\n      type: 'object',\n      properties: {\n        id: {\n          type: 'string',\n          description: 'user id'\n        }\n      }\n    },\n    body: {\n      type: 'object',\n      properties: {\n        hello: { type: 'string' },\n        obj: {\n          type: 'object',\n          properties: {\n            some: { type: 'string' }\n          }\n        }\n      }\n    },\n    response: {\n      201: {\n        description: 'Successful response',\n        type: 'object',\n        properties: {\n          hello: { type: 'string' }\n        }\n      },\n      default: {\n        description: 'Default response',\n        type: 'object',\n        properties: {\n          foo: { type: 'string' }\n        }\n      }\n    },\n    security: [\n      {\n        \"apiKey\": []\n      }\n    ]\n  }\n}, (req, reply) =\u003e {})\n\nawait app.ready()\n```\n\u003ca name=\"api\"\u003e\u003c/a\u003e\n## API\n\n\u003ca name=\"register.options\"\u003e\u003c/a\u003e\n### Register options\n\n#### Options\n\n | Option             | Default         | Description                                                                                                                                                                                                                                       |\n | ------------------ | --------------- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n | baseDir              | undefined       | Specify the directory where all spec files that are included in the main one using $ref will be located. By default, this is the directory where the main spec file is located. Provided value should be an absolute path without trailing slash. |\n | initOAuth            | {}              | Configuration options for [Swagger UI initOAuth](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).                                                                                                                             |\n | routePrefix          | '/documentation' | Overwrite the default Swagger UI route prefix.                                                                                                                                                                                                    |\n | indexPrefix          | '' | Add an additional prefix. This is for when the Fastify server is behind path based routing.  ex. NGINX                                                                                                                                            |\n | staticCSP            | false           | Enable CSP header for static resources.                                                                                                                                                                                                           |\n | transformStaticCSP   | undefined       | Synchronous function to transform CSP header for static resources if the header has been previously set.                                                                                                                                          |\n | transformSpecification     | undefined       | Synchronous function to transform the swagger document.                                                                                                                                                                                           |\n | transformSpecificationClone| true            | Provide a deepcloned swaggerObject to transformSpecification                                                                                                                                                                                      |\n | uiConfig             | {}              | Configuration options for [Swagger UI](https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md).                                                                                                                        |\n | uiHooks              | {}              | Additional hooks for the documentation's routes. You can provide the `onRequest` and `preHandler` hooks with the same [route's options](https://fastify.dev/docs/latest/Reference/Routes/#routes-options) interface.                              |\n | theme                | {}              | Add custom JavaScript and CSS to the Swagger UI web page                                                                                                                                                                                          |\n | logLevel             | info            | Allow to define route log level.                                                                                                                                                                                                                  |\n\nThe plugin will expose the documentation with the following APIs:\n\n| URL                     | Description                                |\n| ----------------------- | ------------------------------------------ |\n| `'/documentation/json'` | The JSON object representing the API       |\n| `'/documentation/yaml'` | The YAML object representing the API       |\n| `'/documentation/'`     | The swagger UI                             |\n| `'/documentation/*'`    | External files that you may use in `$ref`  |\n\n#### uiConfig\n\nTo configure Swagger UI, you need to modify the `uiConfig` option.\nIt's important to ensure that functions are self-contained. Keep in mind that\nyou cannot modify the backend code within the `uiConfig` functions, as these\nfunctions are processed only by the browser. You can reference the Swagger UI\nelement using `ui`, which is assigned to `window.ui`.\n\n##### Example\n```js\nconst fastify = require('fastify')()\n\nawait fastify.register(require('@fastify/swagger'))\n\nawait fastify.register(require('@fastify/swagger-ui'), {\n  uiConfig: {\n    onComplete: function () {\n      alert('ui has type of ' + typeof ui) // 'ui has type of object'\n      alert('fastify has type of ' + typeof fastify) // 'fastify has type of undefined'\n      alert('window has type of ' + typeof window) // 'window has type of object'\n      alert('global has type of ' + typeof global) // 'global has type of undefined'\n    }\n  }\n})\n```\n\n#### transformSpecification\n\nThere can be use cases, where you want to modify the swagger definition on request. E.g. you want to modify the server\ndefinition based on the hostname of the request object. In such a case you can utilize the transformSpecification-option.\n\n##### Example\n```js\nconst fastify = require('fastify')()\n\nawait fastify.register(require('@fastify/swagger'))\n\nawait fastify.register(require('@fastify/swagger-ui'), {\n  transformSpecification: (swaggerObject, req, reply) =\u003e {\n    swaggerObject.host = req.hostname\n    return swaggerObject\n  }\n})\n```\n\nBy default fastify.swagger() will be deepcloned and passed to the transformSpecification-function, as fastify.swagger()\nreturns a mutatable Object. You can disable the deepcloning by setting transformSpecificationClone to false. This is useful,\nif you want to handle the deepcloning in the transformSpecification function.\n\n##### Example with caching\n```js\nconst fastify = require('fastify')()\nconst LRU = require('tiny-lru').lru\nconst rfdc = require('rfdc')()\n\nawait fastify.register(require('@fastify/swagger'))\n\nconst swaggerLru = new LRU(1000)\nawait fastify.register(require('@fastify/swagger-ui'), {\n  transformSpecificationClone: false,\n  transformSpecification: (swaggerObject, req, reply) =\u003e {\n    if (swaggerLru.has(req.hostname)) {\n      return swaggerLru.get(req.hostname)\n    }\n    const clonedSwaggerObject = rfdc(swaggerObject)\n    clonedSwaggerObject.host = req.hostname\n    swaggerLru.set(req.hostname, clonedSwaggerObject)\n    return clonedSwaggerObject\n  }\n})\n```\n\n#### theme\n\nYou can add custom JavaScript and CSS to the Swagger UI web page by using the theme option.\n\n##### Example\n\n```js\nconst fastify = require('fastify')()\n\nawait fastify.register(require('@fastify/swagger'))\n\nawait fastify.register(require('@fastify/swagger-ui'), {\n  theme: {\n    title: 'My custom title',\n    js: [\n      { filename: 'special.js', content: 'alert(\"client javascript\")' }\n    ],\n    css: [\n      { filename: 'theme.css', content: '* { border: 1px red solid; }' }\n    ],\n    favicon: [\n      {\n        filename: 'favicon.png',\n        rel: 'icon',\n        sizes: '16x16',\n        type: 'image/png',\n        content: Buffer.from('iVBOR...', 'base64')\n      }\n    ]\n  }\n})\n```\n\nYou can add custom JavaScript and CSS to the Swagger UI web page by using the theme option.\n\n#### logo\n\nIt's possible to override the logo displayed in the top bar by specifying:\n\n```js\nawait fastify.register(require('@fastify/swagger-ui'), {\n  logo: {\n    type: 'image/png',\n    content: Buffer.from('iVBOR...', 'base64'),\n    href: '/documentation',\n    target: '_blank'\n  },\n  theme: {\n    favicon: [\n      {\n        filename: 'favicon.png',\n        rel: 'icon',\n        sizes: '16x16',\n        type: 'image/png',\n        content: Buffer.from('iVBOR...', 'base64')\n      }\n    ]\n  }\n})\n```\n\n#### Protect your documentation routes\n\nYou can protect your documentation by configuring an authentication hook.\nHere is an example using the [`@fastify/basic-auth`](https://github.com/fastify/fastify-basic-auth) plugin:\n\n##### Example\n```js\nconst fastify = require('fastify')()\nconst crypto = require('node:crypto')\n\nawait fastify.register(require('@fastify/swagger'))\n\n// perform constant-time comparison to prevent timing attacks\nfunction compare (a, b) {\n  a = Buffer.from(a)\n  b = Buffer.from(b)\n  if (a.length !== b.length) {\n    // Delay return with cryptographically secure timing check.\n    crypto.timingSafeEqual(a, a)\n    return false\n  }\n\n  return crypto.timingSafeEqual(a, b)\n}\n\nawait fastify.register(require('@fastify/basic-auth'), {\n  validate (username, password, req, reply, done) {\n    let result = true\n    result = compare(username, validUsername) \u0026\u0026 result\n    result = compare(password, validPassword) \u0026\u0026 result\n    if (result) {\n      done()\n    } else {\n      done(new Error('Access denied'))\n    }\n  },\n  authenticate: true\n})\n\nawait fastify.register(require('@fastify/swagger-ui', {\n  uiHooks: {\n    onRequest: fastify.basicAuth\n  }\n})\n```\n\n#### Rendering models at the bottom of the page\n\nTo ensure that models are correctly rendered at the bottom of the Swagger UI page, it's important to define your schemas using $refs through [fastify.addSchema](https://fastify.dev/docs/latest/Reference/Validation-and-Serialization/#adding-a-shared-schema). Directly embedding JSON schemas within the schema property of your route definitions in Fastify may lead to them not being displayed in Swagger UI.\n\n#### validatorUrl\n\n[SwaggerUI](https://github.com/swagger-api/swagger-ui/) can automatically validate the given specification using an online validator.\nTo enable this behavior you can pass the [`validatorUrl`](https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md) option\nto this plugin which will be forwarded to SwaggerUI.\n\n```js\nawait fastify.register('@fastify/swagger-ui', {\n  validatorUrl: 'https://validator.swagger.io/validator'\n})\n```\n\nNote that this behavior is disabled by default in `@fastify/swagger-ui`.\n\n### Bundling\n\nTo bundle Swagger UI with your application, the swagger-ui static files need to be copied to the server and the `baseDir` option set to point to the file directory.\n\u003cdetails\u003e\n\u003csummary\u003eCopy files with esbuild\u003c/summary\u003e\n\n```js\nimport { build } from 'esbuild'\nimport { copy } from 'esbuild-plugin-copy'\n\nawait build({\n  // ...\n  plugins: [\n    copy({\n      resolveFrom: 'cwd',\n      assets: {\n        from: ['node_modules/@fastify/swagger-ui/static/*'],\n        to: ['dist/static'],\n      },\n    }),\n  ],\n})\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eCopy files with docker\u003c/summary\u003e\n\n```Dockerfile\nCOPY ./node_modules/@fastify/swagger-ui/static /app/static\n```\n\n\u003c/details\u003e\n\n#### Configure Swagger UI to use a custom baseDir\nSet the `baseDir` option to point to your folder.\n\n```js\nawait fastify.register(require('@fastify/swagger-ui'), {\n  baseDir: isDev ? undefined : path.resolve('static'),\n})\n```\n\n\u003ca name=\"license\"\u003e\u003c/a\u003e\n## License\n\nLicensed under [MIT](./LICENSE).\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-swagger-ui","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffastify-swagger-ui","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-swagger-ui/lists"}