1

I have built a project using NestJS along with @nestjs/swagger and swagger-ui-express for API documentation.

Now my docs can be accessible at this path /api/docs but this is absolutely public anyone can access it once I will deploy it to the cloud but I don't wanna do this although most of API's require Bearer token, unfortunately, some of them will remain publically exposed.

Is there any way I can have a login screen for authenticating users before they access my swagger docs?

Here is my code for setting up docs:

import { INestApplication } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import {
  SWAGGER_API_ROOT,
  SWAGGER_API_NAME,
  SWAGGER_API_DESCRIPTION,
  SWAGGER_API_CURRENT_VERSION,
} from './constants';

export const setupSwagger = (app: INestApplication) => {
  const options = new DocumentBuilder()
    .setTitle(SWAGGER_API_NAME)
    .setDescription(SWAGGER_API_DESCRIPTION)
    .setVersion(SWAGGER_API_CURRENT_VERSION)
    .addBearerAuth()
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup(SWAGGER_API_ROOT, app, document);
};

1 Answers1

0

What if you only set the docs in dev mode? You can create an environment var DEV = true or false. After deploy, set it to false and validate with:

if (process.env.DEV) {
    export const setupSwagger = (app: INestApplication) => {
        const options = new DocumentBuilder()
            .setTitle(SWAGGER_API_NAME)
            .setDescription(SWAGGER_API_DESCRIPTION)
            .setVersion(SWAGGER_API_CURRENT_VERSION)
            .addBearerAuth()
            .build();
        const document = SwaggerModule.createDocument(app, options);
        SwaggerModule.setup(SWAGGER_API_ROOT, app, document);
    };
}

Just and idea

MML1357
  • 137
  • 10