Logo

dev-resources.site

for different kinds of informations.

Seamlessly Integrate Swagger with JWT Authentication in NestJS

Published at
11/3/2024
Categories
nestjs
jwt
swagger
webdev
Author
imzihad21
Categories
4 categories in total
nestjs
open
jwt
open
swagger
open
webdev
open
Author
9 person written this
imzihad21
open
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/[email protected]/swagger-ui-bundle.js",
    "https://unpkg.com/[email protected]/swagger-ui-standalone-preset.js",
  ],
  customCssUrl: [  // External CSS files
    "https://unpkg.com/[email protected]/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!

swagger Article's
30 articles in total
Favicon
Crudify: Automate Your Mongoose CRUD Operations in NestJS
Favicon
🚀 API Maker : Release Notes for v1.9.0
Favicon
What Does Swagger x-nullable Mean?
Favicon
Two Reasons on Why We Ship LiveAPI with An ROI Calculator
Favicon
.NET 9 Revolutionizing documentation of APIs : From Swashbuckle to Scalar 🚀
Favicon
What is the Best Way to Group REST API methods in Swagger UI
Favicon
How Scale Changes Everything - The LiveAPI Perspective
Favicon
What is SwaggerHub?
Favicon
Ever wished to maintain API Docs with ease? Introducing LiveAPI: Super Convenient API Docs
Favicon
Integrate Swagger UI with Codeigniter4
Favicon
How to Use Swagger UI Locally: A Step-by-Step Guide
Favicon
Musings Over What Makes LiveAPI Different (from Swagger Et Cetera)
Favicon
Missing Required Key in Body of PUT /odata/Assets({Key}) Edit an asset on UiPath.WebApi 18.0
Favicon
An Online Free API AutoTesting Tool That Completes 160 Hours of Testing Work for 20 APIs in Just 3 Minutes
Favicon
How to Improve Development Efficiency Through Automated API Testing
Favicon
Top 8 Swagger Codegen Alternatives
Favicon
JavaFX In Action #8 with Ulas Ergin: How JavaFX helps to migrate from Swing to React UIs, all combined in one Java app
Favicon
Exploring AutoAPI: An Automation Tool to Simplify Frontend Development
Favicon
Django Rest framework with Swagger
Favicon
Seamlessly Integrate Swagger with JWT Authentication in NestJS
Favicon
New Swagger-UI embedding Cloud TypeScript Editor with RPC SDK
Favicon
Laravel API Documentation Made Easy: Step-by-Step Swagger Integration
Favicon
Introducing Swama: A CLI Tool for Swagger/OpenAPI Interactions
Favicon
StudySpy: Building the new PublicApi v2
Favicon
Swagger UI + Docker: Initial Setup
Favicon
apigen-ts – Simple TypeScript API Client Generator
Favicon
Automating Swagger Documentation with Joi in Node.js: Simplify Your API Documentation Workflow
Favicon
Merge and bundle open api yaml files for swagger
Favicon
Gerando Documentação de API Automática com Fastify, @fastify/swagger e Zod
Favicon
Hosting Swagger-UI using GitHub Pages

Featured ones: