百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
F

fastify-swagger-ui

> 编程语言
开源

为 Fastify 提供 Swagger-UI

193 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

为 Fastify 提供 Swagger-UI

@fastify/swagger-ui

A Fastify plugin for serving Swagger UI.

Install

bash
npm i @fastify/swagger-ui

Compatibility

Plugin version Fastify version Swagger Plugin Version
^5.x ^5.x ^9.x
^2.x ^4.x ^8.x
^1.x ^4.x ^8.x

Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin in the table above. See Fastify's LTS policy for more details.

Usage

Add it with @fastify/swagger to your project with register, pass it some options, call the swagger API, and you are done!

…

Security note: apiKey in the security array is the name of the security scheme declared in components.securitySchemes (OpenAPI 3) or securityDefinitions (Swagger 2.0), not an API key value. The empty array represents scopes and remains empty for API key authentication.

API

Register options

Options

Option Default Description
baseDir undefined Directory from which the Swagger UI static assets (served under /static/) are loaded, instead of the static folder shipped with this plugin. Any other file in that directory is also served relative to routePrefix, e.g. spec files referenced via $ref. When not set, only the bundled Swagger UI assets are served. Provided value should be an absolute path without trailing slash. See Bundling.
initOAuth {} Configuration options for Swagger UI initOAuth.
routePrefix '/documentation' Overwrite the default Swagger UI route prefix.
indexPrefix '' External path prefix added to the asset links in the index page, for when the Fastify server is behind path based routing (e.g. NGINX). See Running behind a reverse proxy.
staticCSP false Enable CSP header for static resources.
transformStaticCSP undefined Synchronous function to transform CSP header for static resources if the header has been previously set.
transformSpecification undefined Synchronous function to transform the swagger document.
transformSpecificationClone true Provide a deepcloned swaggerObject to transformSpecification
uiConfig {} Configuration options for Swagger UI.
uiHooks {} Additional hooks for the documentation's routes. You can provide the onRequest and preHandler hooks with the same route's options interface.
theme {} Add custom JavaScript and CSS to the Swagger UI web page
logLevel info Allow to define route log level.

The plugin will expose the documentation with the following APIs:

URL Description
'/documentation/json' The JSON object representing the API
'/documentation/yaml' The YAML object representing the API
'/documentation/' The swagger UI
'/documentation/*' External files that you may use in $ref

uiConfig

To configure Swagger UI, you need to modify the uiConfig option. It's important to ensure that functions are self-contained. Keep in mind that you cannot modify the backend code within the uiConfig functions, as these functions are processed only by the browser. You can reference the Swagger UI element using ui, which is assigned to window.ui.

Example
javascript
const fastify = require('fastify')()

await fastify.register(require('@fastify/swagger'))

await fastify.register(require('@fastify/swagger-ui'), {
  uiConfig: {
    onComplete: function () {
      alert('ui has type of ' + typeof ui) // 'ui has type of object'
      alert('fastify has type of ' + typeof fastify) // 'fastify has type of undefined'
      alert('window has type of ' + typeof window) // 'window has type of object'
      alert('global has type of ' + typeof global) // 'global has type of undefined'
    }
  }
})
Multiple specifications

Swagger UI can show a "Select a definition" dropdown to switch between several specifications. Pass the urls option through uiConfig:

javascript
await fastify.register(require('@fastify/swagger-ui'), {
  uiConfig: {
    urls: [
      { url: '/documentation/json', name: 'Main API' },
      { url: '/documentation/openapi.yaml', name: 'Other API' }
    ]
  }
})

Each entry is fetched by the browser, so every URL must be reachable from the client (e.g. the spec exposed by this plugin, a file served from baseDir, another Fastify route or an external host). Prefer absolute paths: relative ones (e.g. ./json) are resolved against the page URL, so they only work when the documentation is opened with a trailing slash (/documentation/).

The dropdown is rendered by the topbar of the default StandaloneLayout, so it is not shown if uiConfig.layout is set to BaseLayout. Use urls.primaryName to choose which definition is selected on load:

javascript
uiConfig: {
  urls: [
    { url: '/documentation/json', name: 'Main API' },
    { url: '/documentation/openapi.yaml', name: 'Other API' }
  ],
  'urls.primaryName': 'Other API'
}

The URLs are used as-is: if the server is exposed under an external path prefix (see Running behind a reverse proxy), include that prefix in each url (e.g. /service/documentation/json).

transformSpecification

There can be use cases, where you want to modify the swagger definition on request. E.g. you want to modify the server definition based on the hostname of the request object. In such a case you can utilize the transformSpecification-option.

Example
javascript
const fastify = require('fastify')()

await fastify.register(require('@fastify/swagger'))

await fastify.register(require('@fastify/swagger-ui'), {
  transformSpecification: (swaggerObject, req, reply) => {
    swaggerObject.host = req.hostname
    return swaggerObject
  }
})

By default fastify.swagger() will be deepcloned and passed to the transformSpecification-function, as fastify.swagger() returns a mutatable Object. You can disable the deepcloning by setting transformSpecificationClone to false. This is useful, if you want to handle the deepcloning in the transformSpecification function.

Example with caching
…

theme

You can add custom JavaScript and CSS to the Swagger UI web page by using the theme option.

Example
javascript
const fastify = require('fastify')()

await fastify.register(require('@fastify/swagger'))

await fastify.register(require('@fastify/swagger-ui'), {
  theme: {
    title: 'My custom title',
    js: [
      { filename: 'special.js', content: 'alert("client javascript")' }
    ],
    css: [
      { filename: 'theme.css', content: '* { border: 1px red solid; }' }
    ],
    favicon: [
      {
        filename: 'favicon.png',
        rel: 'icon',
        sizes: '16x16',
        type: 'image/png',
        content: Buffer.from('iVBOR...', 'base64')
      }
    ]
  }
})

You can add custom JavaScript and CSS to the Swagger UI web page by using the theme option.

logo

It's possible to override the logo displayed in the top bar by specifying:

javascript
await fastify.register(require('@fastify/swagger-ui'), {
  logo: {
    type: 'image/png',
    content: Buffer.from('iVBOR...', 'base64'),
    href: '/documentation',
    target: '_blank'
  },
  theme: {
    favicon: [
      {
        filename: 'favicon.png',
        rel: 'icon',
        sizes: '16x16',
        type: 'image/png',
        content: Buffer.from('iVBOR...', 'base64')
      }
    ]
  }
})

Protect your documentation routes

You can protect your documentation by configuring an authentication hook. Here is an example using the @fastify/basic-auth plugin:

Example
…

Rendering models at the bottom of the page

To 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. Directly embedding JSON schemas within the schema property of your route definitions in Fastify may lead to them not being displayed in Swagger UI.

validatorUrl

SwaggerUI can automatically validate the given specification using an online validator. To enable this behavior you can pass the validatorUrl option to this plugin which will be forwarded to SwaggerUI.

javascript
await fastify.register('@fastify/swagger-ui', {
  validatorUrl: 'https://validator.swagger.io/validator'
})

Note that this behavior is disabled by default in @fastify/swagger-ui.

Running behind a reverse proxy

When Fastify sits behind a proxy that strips a path prefix (e.g. NGINX serving your app under /service and forwarding /service/documentation as `/d

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

JavaScriptdocumentationfastifyfastify-pluginopenapi

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言