Swagger Integration
⭐ Interview Importance: HIGH
⏱️ Revision Time: 5 min
Swagger Integration in NestJS refers to the process of installing, configuring, and bootstrapping the @nestjs/swagger module so that your application serves an interactive OpenAPI dashboard.
Overview
Setting up Swagger in NestJS takes only a few lines of code in your main.ts file. Once configured, NestJS will scan all of your controllers and modules during startup, build the OpenAPI specification tree, and serve it via a built-in Swagger UI HTML page.
Key Concepts
DocumentBuilder: A fluent API/Builder pattern used to configure the root properties of your OpenAPI document (like Title, Description, Version, and global Authentication requirements).SwaggerModule.createDocument(): The function that actually scans your app and builds the JSON schema.SwaggerModule.setup(): The function that binds the generated document to a specific URL route (e.g.,/apior/docs) and serves the UI.
Code Examples
1. Installation
First, you must install the required packages.
npm install @nestjs/swagger swagger-ui-express
2. Basic Setup in main.ts
This is the standard boilerplate required to get Swagger running.
// main.ts
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// 1. Create the configuration builder
const config = new DocumentBuilder()
.setTitle('E-Commerce API')
.setDescription('The internal API used for the mobile app and web frontend.')
.setVersion('1.0')
.addTag('users', 'Operations related to user management') // Optional global tags
.addTag('products')
.build();
// 2. Generate the document based on the configuration and app modules
const document = SwaggerModule.createDocument(app, config);
// 3. Serve the interactive UI at the '/docs' route
// The JSON representation will be available at '/docs-json'
SwaggerModule.setup('docs', app, document);
await app.listen(3000);
console.log(`Application is running on: http://localhost:3000`);
console.log(`Swagger UI is running on: http://localhost:3000/docs`);
}
bootstrap();
3. Advanced Setup Configuration
You can customize the Swagger UI experience by passing options to the setup method.
const options = {
swaggerOptions: {
// Automatically persist authorization token across browser refreshes!
persistAuthorization: true,
// Collapse all endpoints by default so the UI isn't overwhelmingly long
docExpansion: 'none',
// Filter endpoints via a search bar
filter: true,
},
// Add a custom title to the HTML page tab
customSiteTitle: 'My Company API Docs',
};
SwaggerModule.setup('docs', app, document, options);
Best Practices
- Environment Checks: You almost never want to expose Swagger to the public internet on a production server, as it gives hackers a perfect map of your API. Wrap the
SwaggerModule.setupcode in an environment check (e.g.,if (process.env.NODE_ENV !== 'production')). - Use the CLI Plugin: While integrating Swagger is easy, adding
@ApiProperty()to every single DTO field is tedious. Always enable the NestJS CLI Swagger Plugin in yournest-cli.jsonto have NestJS automatically infer types from your TypeScript code.