NestJS course Β· Module 11: Swagger and OpenAPI
Swagger UI Customization - Decorating the Forum of Annals
In this lesson9
Just as the Forum Romanum was decorated with columns, statues, and frescoes, our Swagger UI can be customized visually and functionally. NestJS offers many options for personalizing the documentation interface.
SwaggerModule.setup() Options
The fourth parameter of the setup() method allows for advanced configuration:
SwaggerModule.setup('api/docs', app, document, {
customSiteTitle: 'Chronicles of Imperium Romanum',
customCss: '.swagger-ui .topbar { background-color: #8B0000; }',
swaggerOptions: {
persistAuthorization: true,
docExpansion: 'none',
filter: true,
showRequestDuration: true,
tryItOutEnabled: true,
},
});customSiteTitle - Name of the Notice Board
Changes the page title in the browser:
SwaggerModule.setup('api/docs', app, document, {
customSiteTitle: 'Imperium API - Documentation',
});customCss - Frescoes on the Walls
Allows you to add custom CSS styles to Swagger UI:
SwaggerModule.setup('api/docs', app, document, {
customCss: `
.swagger-ui .topbar { background-color: #8B0000; }
.swagger-ui .topbar-wrapper img { content: url('/logo.png'); }
.swagger-ui .info .title { color: #8B0000; }
.swagger-ui .btn.execute { background-color: #8B0000; }
`,
});swaggerOptions - Forum Regulations
Options controlling the behavior of Swagger UI:
| Option | Description | Default |
|---|---|---|
persistAuthorization | Keep JWT token after refresh | false |
docExpansion | Default section expansion | 'list' |
filter | Show search field | false |
showRequestDuration | Show response time | false |
tryItOutEnabled | Testing mode enabled by default | false |
defaultModelsExpandDepth | Model expansion depth | 1 |
defaultModelExpandDepth | Model field expansion depth | 1 |
SwaggerModule.setup('api/docs', app, document, {
swaggerOptions: {
persistAuthorization: true,
docExpansion: 'none',
filter: true,
showRequestDuration: true,
},
});addBearerAuth - Authorization Configuration
Full JWT authentication configuration in Swagger:
const config = new DocumentBuilder()
.setTitle('Imperium API')
.addBearerAuth(
{
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
name: 'JWT',
description: 'Enter JWT token',
in: 'header',
},
'JWT-auth',
)
.build();After this configuration, an "Authorize" button will appear in Swagger UI where the user can enter their JWT token.
operationIdFactory - Operation Names
Every operation in OpenAPI has a unique operationId. You can control how they are generated:
const document = SwaggerModule.createDocument(app, config, {
operationIdFactory: (controllerKey: string, methodKey: string) =>
methodKey,
});By default, NestJS generates operationId in the format ControllerName_methodName. The above setting will use only the method name.
createDocument Options
The createDocument() method accepts additional options:
const document = SwaggerModule.createDocument(app, config, {
// Include only selected modules
include: [LegionModule, ProvinceModule],
// Schema nesting depth
deepScanRoutes: true,
// Custom operationId generator
operationIdFactory: (controllerKey, methodKey) => methodKey,
// Additional models to include
extraModels: [ErrorResponseDto, PaginatedResponseDto],
});Securing the Documentation
In a production environment, it is worth securing access to Swagger UI:
import * as basicAuth from 'express-basic-auth';
// Before SwaggerModule.setup()
app.use(
'/api/docs',
basicAuth({
challenge: true,
users: { admin: 'imperiumSecret123' },
}),
);
SwaggerModule.setup('api/docs', app, document);Practical Exercise
Configure advanced Swagger UI options for the Imperium project:
Code for this lesson: src/main.ts
// Swagger UI customization
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
// const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('Imperium Romanum API')
.setDescription('Imperium API Chronicles')
.setVersion('1.0')
// TODO: Add addBearerAuth with a full configuration:
// type: 'http', scheme: 'bearer', bearerFormat: 'JWT'
.build();
// const document = SwaggerModule.createDocument(app, config);
// TODO: Configure SwaggerModule.setup with options:
// customSiteTitle: 'Imperium API Chronicles'
// swaggerOptions:
// persistAuthorization: true
// docExpansion: 'none'
// filter: true
// showRequestDuration: true
// SwaggerModule.setup('api/docs', app, document, {
// // TODO: Add customSiteTitle
// // TODO: Add swaggerOptions
// });
console.log("Swagger UI: http://localhost:3000/api/docs");
}
bootstrap();
console.log("=== Customization options ===");
console.log("customSiteTitle - page title");
console.log("customCss - custom CSS styles");
console.log("swaggerOptions.persistAuthorization - keep the token");
console.log("swaggerOptions.docExpansion - section expansion");
console.log("swaggerOptions.filter - search field");
console.log("swaggerOptions.showRequestDuration - response time");
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the persistAuthorization option do in swaggerOptions?
2. What does the customSiteTitle option change in the SwaggerModule.setup() configuration?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Complete the SwaggerModule.setup options with customSiteTitle and swaggerOptions
- Horizontal ordering
Arrange the elements of the addBearerAuth configuration in the correct order:
- Code editor
Add full Swagger documentation (tags, operation, params, responses, auth) to the gladiator controller