scottie1984 / swagger-ui-express

Adds middleware to your express app to serve the Swagger UI bound to your Swagger document. This acts as living documentation for your API hosted from within your app.
MIT License
1.4k stars 225 forks source link

DocumentBuilder.addServer() with https generates incorrect base path url, rendering all of swagger docs useless #337

Open tatianajiselle opened 1 year ago

tatianajiselle commented 1 year ago

Same issue as reported here: https://github.com/nestjs/swagger/issues/1217 but was unable to track down an issue in this repo so opening ...

We are initalizing a swagger module via nestjs. After bumping our package version for swagger, we had to make the change from setSchemas to addServer for the document builder. With our update to addServer(http ? http : https) when https is enabled we see in our swagger calls that the path to the /openapi docs are appended to all api requests. This makes the entire swagger documentation useless because every endpoint 404s.

P.S. theres no documentation on addServer and examples are pretty minimal, consider updating documentation to prevent future issues.

ex:

our-service.com/openapi

takes us to swagger specs. When we query from there, we get the following dns:

ex:

https://www.our-service.com/openapi/api/v1/do-something

when it should be

https://www.our-service.com/api/v1/do-something

Expected behavior: addServer() should properly inherit base url instead of passing through the /openapi path

Config:

import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; ///    "@nestjs/swagger": "5.2.1"

  const app = await NestFactory.create(AppModule, appOptions);

    const options = new DocumentBuilder()
      .setTitle(packageJSON.name)
      .setDescription(packageJSON.description)
      .setVersion(packageJSON.version)
      .addServer(process.env.SWAGGER_SCHEME === 'http' ? 'http' : 'https')
      .addBearerAuth({ type: 'http', description: 'JWT Bearer header' }, 'elevated-user')
      .addBearerAuth({ type: 'http', description: 'AccessToken' }, 'access-token')
      .build();
    const document = SwaggerModule.createDocument(app, options);

    SwaggerModule.setup('/openapi', app, document);

Extra info:

When I print out the document object on the older version with setSchemas, I see the base path is defined as /

{
  swagger: '2.0',
  info: {
    description: 'service to track abad and econsent permissions for a user across ZG',
    version: '0.0.0',
    title: 'abad-econsent'
  },
  basePath: '/',
  tags: [],
  schemes: [ 'http' ],
  ... }

in the addServer() document object it is missing, I presume this is what is causing the error.

Please advise!