Installations
npm install @fastify/swagger-ui
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
20.18.1
NPM Version
10.8.2
Score
68.9
Supply Chain
99.2
Quality
93.4
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Languages
JavaScript (92.2%)
TypeScript (7.8%)
Developer
Download Statistics
Total Downloads
15,127,649
Last Day
42,582
Last Week
199,307
Last Month
894,390
Last Year
9,666,957
GitHub Statistics
151 Stars
182 Commits
43 Forks
12 Watching
3 Branches
47 Contributors
Sponsor this package
Package Meta Information
Latest Version
5.2.1
Package Id
@fastify/swagger-ui@5.2.1
Unpacked Size
2.21 MB
Size
595.56 kB
File Count
66
NPM Version
10.8.2
Node Version
20.18.1
Publised On
10 Jan 2025
Total Downloads
Cumulative downloads
Total Downloads
15,127,649
Last day
-16%
42,582
Compared to previous day
Last week
-16.5%
199,307
Compared to previous week
Last month
3.2%
894,390
Compared to previous month
Last year
86.3%
9,666,957
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
@fastify/swagger-ui
A Fastify plugin for serving Swagger UI.
Install
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!
1import fastify from 'fastify' 2 3const app = fastify() 4 5await app.register(import('@fastify/swagger')) 6 7await app.register(import('@fastify/swagger-ui'), { 8 routePrefix: '/documentation', 9 uiConfig: { 10 docExpansion: 'full', 11 deepLinking: false 12 }, 13 uiHooks: { 14 onRequest: function (request, reply, next) { next() }, 15 preHandler: function (request, reply, next) { next() } 16 }, 17 staticCSP: true, 18 transformStaticCSP: (header) => header, 19 transformSpecification: (swaggerObject, request, reply) => { return swaggerObject }, 20 transformSpecificationClone: true 21}) 22 23app.put('/some-route/:id', { 24 schema: { 25 description: 'post some data', 26 tags: ['user', 'code'], 27 summary: 'qwerty', 28 params: { 29 type: 'object', 30 properties: { 31 id: { 32 type: 'string', 33 description: 'user id' 34 } 35 } 36 }, 37 body: { 38 type: 'object', 39 properties: { 40 hello: { type: 'string' }, 41 obj: { 42 type: 'object', 43 properties: { 44 some: { type: 'string' } 45 } 46 } 47 } 48 }, 49 response: { 50 201: { 51 description: 'Successful response', 52 type: 'object', 53 properties: { 54 hello: { type: 'string' } 55 } 56 }, 57 default: { 58 description: 'Default response', 59 type: 'object', 60 properties: { 61 foo: { type: 'string' } 62 } 63 } 64 }, 65 security: [ 66 { 67 "apiKey": [] 68 } 69 ] 70 } 71}, (req, reply) => {}) 72 73await app.ready()
API
Register options
Options
Option | Default | Description |
---|---|---|
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. |
initOAuth | {} | Configuration options for Swagger UI initOAuth. |
routePrefix | '/documentation' | Overwrite the default Swagger UI route prefix. |
indexPrefix | '' | Add an additional prefix. This is for when the Fastify server is behind path based routing. ex. NGINX |
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
1const fastify = require('fastify')() 2 3await fastify.register(require('@fastify/swagger')) 4 5await fastify.register(require('@fastify/swagger-ui'), { 6 uiConfig: { 7 onComplete: function () { 8 alert('ui has type of ' + typeof ui) // 'ui has type of object' 9 alert('fastify has type of ' + typeof fastify) // 'fastify has type of undefined' 10 alert('window has type of ' + typeof window) // 'window has type of object' 11 alert('global has type of ' + typeof global) // 'global has type of undefined' 12 } 13 } 14})
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
1const fastify = require('fastify')() 2 3await fastify.register(require('@fastify/swagger')) 4 5await fastify.register(require('@fastify/swagger-ui'), { 6 transformSpecification: (swaggerObject, req, reply) => { 7 swaggerObject.host = req.hostname 8 return swaggerObject 9 } 10})
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
1const fastify = require('fastify')() 2const LRU = require('tiny-lru').lru 3const rfdc = require('rfdc')() 4 5await fastify.register(require('@fastify/swagger')) 6 7const swaggerLru = new LRU(1000) 8await fastify.register(require('@fastify/swagger-ui'), { 9 transformSpecificationClone: false, 10 transformSpecification: (swaggerObject, req, reply) => { 11 if (swaggerLru.has(req.hostname)) { 12 return swaggerLru.get(req.hostname) 13 } 14 const clonedSwaggerObject = rfdc(swaggerObject) 15 clonedSwaggerObject.host = req.hostname 16 swaggerLru.set(req.hostname, clonedSwaggerObject) 17 return clonedSwaggerObject 18 } 19})
theme
You can add custom JavaScript and CSS to the Swagger UI web page by using the theme option.
Example
1const fastify = require('fastify')() 2 3await fastify.register(require('@fastify/swagger')) 4 5await fastify.register(require('@fastify/swagger-ui'), { 6 theme: { 7 title: 'My custom title', 8 js: [ 9 { filename: 'special.js', content: 'alert("client javascript")' } 10 ], 11 css: [ 12 { filename: 'theme.css', content: '* { border: 1px red solid; }' } 13 ], 14 favicon: [ 15 { 16 filename: 'favicon.png', 17 rel: 'icon', 18 sizes: '16x16', 19 type: 'image/png', 20 content: Buffer.from('iVBOR...', 'base64') 21 } 22 ] 23 } 24})
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:
1await fastify.register(require('@fastify/swagger-ui'), { 2 logo: { 3 type: 'image/png', 4 content: Buffer.from('iVBOR...', 'base64'), 5 href: '/documentation', 6 target: '_blank' 7 }, 8 theme: { 9 favicon: [ 10 { 11 filename: 'favicon.png', 12 rel: 'icon', 13 sizes: '16x16', 14 type: 'image/png', 15 content: Buffer.from('iVBOR...', 'base64') 16 } 17 ] 18 } 19})
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
1const fastify = require('fastify')() 2const crypto = require('node:crypto') 3 4await fastify.register(require('@fastify/swagger')) 5 6// perform constant-time comparison to prevent timing attacks 7function compare (a, b) { 8 a = Buffer.from(a) 9 b = Buffer.from(b) 10 if (a.length !== b.length) { 11 // Delay return with cryptographically secure timing check. 12 crypto.timingSafeEqual(a, a) 13 return false 14 } 15 16 return crypto.timingSafeEqual(a, b) 17} 18 19await fastify.register(require('@fastify/basic-auth'), { 20 validate (username, password, req, reply, done) { 21 let result = true 22 result = compare(username, validUsername) && result 23 result = compare(password, validPassword) && result 24 if (result) { 25 done() 26 } else { 27 done(new Error('Access denied')) 28 } 29 }, 30 authenticate: true 31}) 32 33await fastify.register(require('@fastify/swagger-ui', { 34 uiHooks: { 35 onRequest: fastify.basicAuth 36 } 37})
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.
1await fastify.register('@fastify/swagger-ui', { 2 validatorUrl: 'https://validator.swagger.io/validator' 3})
Note that this behavior is disabled by default in @fastify/swagger-ui
.
Bundling
To 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.
Copy files with esbuild
1import { build } from 'esbuild' 2import { copy } from 'esbuild-plugin-copy' 3 4await build({ 5 // ... 6 plugins: [ 7 copy({ 8 resolveFrom: 'cwd', 9 assets: { 10 from: ['node_modules/@fastify/swagger-ui/static/*'], 11 to: ['dist/static'], 12 }, 13 }), 14 ], 15})
Copy files with docker
1COPY ./node_modules/@fastify/swagger-ui/static /app/static
Configure Swagger UI to use a custom baseDir
Set the baseDir
option to point to your folder.
1await fastify.register(require('@fastify/swagger-ui'), { 2 baseDir: isDev ? undefined : path.resolve('static'), 3})
License
Licensed under MIT.
Stable Version
Stable Version
5.2.1
MODERATE
1
5.3/10
Summary
Default swagger-ui configuration exposes all files in the module
Affected Versions
>= 2.0.0, < 2.1.0
Patched Versions
2.1.0
No security vulnerabilities found.