Nx NestJs | Autogenerate OpenApi/Swagger from DTO
2 min readJun 24, 2024
This is a guide on how to configure Nest/Swagger with an NX monorepo using NestJS.
Version used
Nx V19.3.1
Nestjs V10.3.9
Create our project
npx create-nx-workspace
Install @nestjs/swagger
npm install --save @nestjs/swagger
then add SwaggerModule on bootstrap()
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app/app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const globalPrefix = 'api';
app.setGlobalPrefix(globalPrefix);
const port = process.env.PORT || 3000;
//add SwaggerModule on bootstrap()
const config = new DocumentBuilder().setTitle('API Documentation').setVersion('1.0').addTag('api').build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('swagger', app, document);
//end
await app.listen(port);
Logger.log(`🚀 Application is running on: http://localhost:${port}/${globalPrefix}`);
}
bootstrap();
Apply @nestjs/swagger/plugin
Option 1: Edit webpack.config.js
Add “ transformers: [{ name: ‘@nestjs/swagger/plugin’ }]” into webpack.config.js file
const { NxAppWebpackPlugin } = require('@nx/webpack/app-plugin');
const { join } = require('path');
module.exports = {
output: {
path: join(__dirname, '../../dist/apps/my-app'),
},
plugins: [
new NxAppWebpackPlugin({
target: 'node',
compiler: 'tsc',
main: './src/main.ts',
tsConfig: './tsconfig.app.json',
assets: ["./src/assets"],
optimization: false,
outputHashing: 'none',
transformers: [{ name: '@nestjs/swagger/plugin' }],
})
],
};
Option 2: Edit project.json
You need to add the “@nestjs/swagger/plugin” into your project.json file within your application.
{
"name": "my-app",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/my-app/src",
"projectType": "application",
"tags": [],
"targets": {
"serve": {
"executor": "@nx/js:node",
"defaultConfiguration": "development",
"options": {
"buildTarget": "my-app:build"
},
"configurations": {
"development": {
"buildTarget": "my-app:build:development"
},
"production": {
"buildTarget": "my-app:build:production"
}
}
},
"build": {
"executor": "@nx/js:tsc",
"outputs": [
"{options.outputPath}"
],
"options": {
"outputPath": "dist/apps/my-app",
"main": "apps/my-app/src/main.ts",
"tsConfig": "apps/my-app/tsconfig.app.json",
"transformers": [
{
"name": "@nestjs/swagger/plugin",
"options": {
"introspectComments": true
}
}
]
}
}
}
}
Create API and DTO for testing
//test.dto.ts
export class TestDto {
requirefield: string;
optionalfield?: string;
}
//app.service.ts
import { Injectable } from '@nestjs/common';
import { TestDto } from './test.dto';
@Injectable()
export class AppService {
getData(): TestDto {
const test: TestDto = {
requirefield: 'test',
}
return test;
}
}
//app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getData() {
return this.appService.getData();
}
}
Verify result
Read more
Generete type for Frontend from OpenApi/Swagger
Reference
Any idea on how to use nestjs cli plugin with nx?: https://github.com/nrwl/nx/issues/4135