DEV Community

Cover image for Seamlessly Integrate Swagger with JWT Authentication in NestJS
Mofajjal Rasul
Mofajjal Rasul

Posted on • Edited on

2

Seamlessly Integrate Swagger with JWT Authentication in NestJS

Enhancing your NestJS API with robust documentation and JWT authentication is essential for a smooth developer experience. In this article, we'll walk you through integrating Swagger UI into your NestJS application, utilizing dummy data, and customizing the UI with external assets.

Step 1: Install Required Packages

Start by installing the necessary packages for Swagger support:

npm install @nestjs/swagger
Enter fullscreen mode Exit fullscreen mode

Step 2: Create Swagger Configuration

Create a file (swagger.config.ts), configure Swagger using the following code snippet with dummy data for demonstration:

import { INestApplication } from "@nestjs/common";
import {
  DocumentBuilder,
  SwaggerCustomOptions,
  SwaggerModule,
} from "@nestjs/swagger";

const documentConfig = new DocumentBuilder()
  .setTitle("Dummy API")  // API Title
  .setVersion("1.0.0")  // API Version
  .addBearerAuth(  // Adds JWT Bearer authentication
    {
      type: "http",
      scheme: "bearer",
      bearerFormat: "JWT",
      name: "Authorization",
      description: "Enter JWT token",
      in: "header",
    },
    "Bearer",
  )
  .addSecurityRequirements("Bearer")  // Security requirement
  .build();

const swaggerUiOptions: SwaggerCustomOptions = {
  swaggerOptions: {
    persistAuthorization: true,  // Retain authorization
  },
  customSiteTitle: "Dummy API Documentation",  // Swagger UI title
  customJs: [  // External JS files
    "https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui-bundle.js",
    "https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui-standalone-preset.js",
  ],
  customCssUrl: [  // External CSS files
    "https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui.css",
  ],
};

// Function to configure Swagger UI
export const configureSwaggerUI = (app: INestApplication<any>) => {
  const document = SwaggerModule.createDocument(app, documentConfig);  // Create Swagger document
  SwaggerModule.setup("swagger", app, document, swaggerUiOptions);  // Setup Swagger UI
};
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Document Configuration: Set up a Swagger document with a title, version, and authentication.
  • Swagger UI Options: Configure options, including a custom title and external assets.

Step 3: Integrate Swagger in Your NestJS Application

Add the Swagger configuration in your main.ts file:

import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { configureSwaggerUI } from "./swagger.config";  // Import Swagger configuration

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  configureSwaggerUI(app);  // Configure Swagger
  await app.listen(4000);  // Start the application
}

bootstrap();
Enter fullscreen mode Exit fullscreen mode

Step 4: Run Your Application

Now, run your NestJS application:

npm run start
Enter fullscreen mode Exit fullscreen mode

Step 5: Access Swagger UI

Open your browser and navigate to:

http://localhost:4000/swagger
Enter fullscreen mode Exit fullscreen mode

You should see the Swagger UI with your Dummy API documentation!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay