To use @fastify/swagger-ui, you must first register @fastify/swagger in your project. Then, register @fastify/swagger-ui with your desired configuration options.
Key configuration options include:
routePrefix: The URL path where the Swagger UI will be served.uiConfig: Configuration for the Swagger UI interface (e.g., docExpansion, deepLinking).uiHooks: Lifecycle hooks for the UI requests (onRequest, preHandler).staticCSP: Boolean to enable static Content Security Policy.transformStaticCSP: Function to transform the CSP header.transformSpecification: Function to transform the Swagger/OpenAPI specification object.transformSpecificationClone: Boolean to determine if the specification should be cloned before transformation.
Security Note: When defining security in your route schemas, the key (e.g., apiKey) must match the name of the security scheme declared in components.securitySchemes (OpenAPI 3) or securityDefinitions (Swagger 2.0). The empty array [] represents scopes and is used for API key authentication.
import fastify from 'fastify'
const app = fastify()
// 1. Register @fastify/swagger first
await app.register(import('@fastify/swagger'))
// 2. Register @fastify/swagger-ui
await app.register(import('@fastify/swagger-ui'), {
routePrefix: '/documentation',
uiConfig: {
docExpansion: 'full',
deepLinking: false
},
uiHooks: {
onRequest: function (request, reply, next) { next() },
preHandler: function (request, reply, next) { next() }
},
staticCSP: true,
transformStaticCSP: (header) => header,
transformSpecification: (swaggerObject, request, reply) => { return swaggerObject },
transformSpecificationClone: true
})
// 3. Define routes with schemas
app.put('/some-route/:id', {
schema: {
description: 'post some data',
tags: ['user', 'code'],
summary: 'qwerty',
params: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'user id'
}
}
},
body: {
type: 'object',
properties: {
hello: { type: 'string' },
obj: {
type: 'object',
properties: {
some: { type: 'string' }
}
}
}
},
response: {
201: {
description: 'Successful response',
type: 'object',
properties: {
hello: { type: 'string' }
}
},
default: {
description: 'Default response',
type: 'object',
properties: {
foo: { type: 'string' }
}
}
},
security: [
{
"apiKey": []
}
]
}
}, (req, reply) => {})
await app.ready()