swagger-api / swagger-ui

Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.
https://swagger.io
Apache License 2.0
26.56k stars 8.95k forks source link

When deploying swagger on vercel on nodejs it does not show UI #8461

Open Milan-960 opened 1 year ago

Milan-960 commented 1 year ago

This is How it does look like this and I do not know how to fix this issue.

Q&A (please complete the following information)

Content & configuration

Swagger/OpenAPI definition:

# your YAML here

Swagger-UI configuration options:

SwaggerUI({
  // your config options here
const options = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "Library API",
      version: "1.0.0",
      description: "A simple Express Library API",
      termsOfService: "http://example.com/terms/",
      contact: {
        name: "API Support",
        url: "http://www.exmaple.com/support",
        email: "support@example.com",
      },
    },
    servers: [
      {
        url: "https://localhost:2001",
        description: "My API Documentation",
      },
    ],
  },
  // This is to call all the files
  apis: ["src/**/*.js"],
};
})
?yourQueryStringConfig

Screenshots

Screenshot 2023-03-08 at 19 31 06 Screenshot 2023-03-08 at 19 35 29

How can we help?

I have built a backend on node.js and after deploying swagger on vercel it does not show UI for api-docs rest of the things are working as they should. Also, I have added custom HTML as well which is also working you can check the SS.

Milan-960 commented 1 year ago

Am I missing something to add? app.use("/api-docs", swaggerUI.serve, swaggerUI.setup(specs));

fedotovdev commented 1 year ago

The same issue I have. Did you solved it?

Milan-960 commented 1 year ago

Yes, I did :) but it was not a more sufficient way to do that! but I had resolved the issue!

jcs-2020 commented 1 year ago

Hi i am having the same issues can you help me out?

Milan-960 commented 1 year ago

@jcs-2020 sure! It is not a sufficient way to do it but there are no other options!

you can directly use CDN // CDN CSS const CSS_URL = "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.1.0/swagger-ui.min.css";

and pass it down to your app.use where you have swagger api-docs

swaggerUI.setup(specs, { customCssUrl: CSS_URL })

and boom it should work :)

you also can check out my repo as well :) https://github.com/Milan-960/Nodejs-swagger-api/blob/master/index.js

shivam-os commented 1 year ago

Thanks, it worked!

MOA-CODES commented 1 year ago

Hey my problem is that my swaggerUI doesn't show at all. any help?

I deployed using vercel and when I click my link that should take me to my link it doesn't show anything.

I didn't have any issues when I was using heroku though, didn't have to use path.resolve for my swagger.yaml document, or it not displaying at all.

Milan-960 commented 1 year ago

Hey @MOA-CODES it should work then if you have deployed to Vercel there are a few things we might need to take care of while deploying however if it does not show any error after it has been deployed successfully you should be able to see the UI

You can check out this Repo if it might help you when you deployed on Vercel https://github.com/Milan-960/Nodejs-swagger-api/blob/master/index.js

or if you could share the Link to your repo or any console error or something which will help to find the solution :) and can help you to resolve that!

MOA-CODES commented 1 year ago

There wasn't any console error, the first I had an error with the swaggerui, was that it made my app crash on vercel. So I had to go back use path.resolve so that it could find my .YAML file.

Then after that, the app started working but when I clicked on my link that should take me to my swagger documentation nothing is displayed.

This is the github repo.

https://github.com/MOACODES/VERCEL_JOBS_API

Sorry for my late reply, your help is much appreciated

On Tue, 8 Aug 2023, 09:14 Milan Sachani, @.***> wrote:

Hey @MOA-CODES https://github.com/MOA-CODES it should work then if you have deployed to Vercel there are a few things we might need to take care of while deploying however if it does not show any error after it has been deployed successfully you should be able to see the UI

You can check out this Repo if it might help you when you deployed on Vercel https://github.com/Milan-960/Nodejs-swagger-api/blob/master/index.js

or if you could share the Link to your repo or any console error or something which will help to find the solution :) and can help you to resolve that!

— Reply to this email directly, view it on GitHub https://github.com/swagger-api/swagger-ui/issues/8461#issuecomment-1669133079, or unsubscribe https://github.com/notifications/unsubscribe-auth/AXDXEVAPFFEM5KAU6BJCRVLXUHYPBANCNFSM6AAAAAAVUDVEWQ . You are receiving this because you were mentioned.Message ID: @.***>

VenkateshMogili commented 1 year ago

@jcs-2020 sure! It is not a sufficient way to do it but there are no other options!

you can directly use CDN // CDN CSS const CSS_URL = "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.1.0/swagger-ui.min.css";

and pass it down to your app.use where you have swagger api-docs

swaggerUI.setup(specs, { customCssUrl: CSS_URL })

and boom it should work :)

you also can check out my repo as well :) https://github.com/Milan-960/Nodejs-swagger-api/blob/master/index.js

Thank you, it worked for me🎉🎉🎉🥳

In my project, swagger-ui-express version is 4.3.0, the same version I replaced, then it worked properly.

https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.3.0/swagger-ui.min.css

MOA-CODES commented 1 year ago

Thanks, man it works now, my version was 5.0.0 downgraded it to 4.3.0, and it shows now.

Bless up.💪🏾

On Tue, Aug 15, 2023 at 1:05 PM VenkateshMogili @.***> wrote:

@jcs-2020 https://github.com/jcs-2020 sure! It is not a sufficient way to do it but there are no other options!

you can directly use CDN // CDN CSS const CSS_URL = " https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.1.0/swagger-ui.min.css ";

and pass it down to your app.use where you have swagger api-docs

swaggerUI.setup(specs, { customCssUrl: CSS_URL })

and boom it should work :)

you also can check out my repo as well :) https://github.com/Milan-960/Nodejs-swagger-api/blob/master/index.js

Thank you, it worked for me🎉🎉🎉🥳

In my project, swagger-ui-express version is 4.3.0, the same version I replaced, then it worked properly.

https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.3.0/swagger-ui.min.css

— Reply to this email directly, view it on GitHub https://github.com/swagger-api/swagger-ui/issues/8461#issuecomment-1678820322, or unsubscribe https://github.com/notifications/unsubscribe-auth/AXDXEVBBAWEGHP2I3BQIJKTXVNQXRANCNFSM6AAAAAAVUDVEWQ . You are receiving this because you were mentioned.Message ID: @.***>

Melifen commented 1 year ago

Thanks, man it works now, my version was 5.0.0 downgraded it to 4.3.0, and it shows now. Bless up.💪🏾 On Tue, Aug 15, 2023 at 1:05 PM VenkateshMogili @.> wrote: @jcs-2020 https://github.com/jcs-2020 sure! It is not a sufficient way to do it but there are no other options! you can directly use CDN // CDN CSS const CSS_URL = " https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.1.0/swagger-ui.min.css "; and pass it down to your app.use where you have swagger api-docs swaggerUI.setup(specs, { customCssUrl: CSS_URL }) and boom it should work :) you also can check out my repo as well :) https://github.com/Milan-960/Nodejs-swagger-api/blob/master/index.js Thank you, it worked for me🎉🎉🎉🥳 In my project, swagger-ui-express version is 4.3.0, the same version I replaced, then it worked properly. https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.3.0/swagger-ui.min.css — Reply to this email directly, view it on GitHub <#8461 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AXDXEVBBAWEGHP2I3BQIJKTXVNQXRANCNFSM6AAAAAAVUDVEWQ . You are receiving this because you were mentioned.Message ID: @.>

I met the same problem with you. Thank you for your method. I'm going to downgrade my package version now. 😊

MOA-CODES commented 1 year ago

Your welcome bro

DaviidMM commented 11 months ago

Thanks for your solution, @Milan-960 but it didn't fully solve my issue, all of the request summaries were messed up as you can see here:

image

My solution was similar, but I added custom css to display summaries properly.

// Route-Handler to visit our docs
route.use(
  '/docs',
  swaggerUi.serve,
  swaggerUi.setup(swaggerSpec, {
    customCss:
      '.swagger-ui .opblock .opblock-summary-path-description-wrapper { align-items: center; display: flex; flex-wrap: wrap; gap: 0 10px; padding: 0 10px; width: 100%; }',
    customCssUrl: CSS_URL,
  }),
);

image

I don't think this is the best solution but at least it works... If anyone has a better solution, feel free to share it!

Full code can be found here: https://github.com/DaviidMM/api-auvasa

m0x61h0x64i commented 11 months ago

Finally there is a third problem as @DaviidMM has! I already solved first two problems before and now i didnt update anything but ran into this new issue where summaries divided into segments! im using vercel.

"swagger-jsdoc": "^6.2.8" "swagger-ui-express": "^4.6.3"

m0x61h0x64i commented 10 months ago

This time I deployed a nest app and now nothing loads on both android and desktop! I also used customCssUrl... "@nestjs/swagger": "^7.1.17",

image

UPDATE: solved it using : customJs: [ 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-bundle.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-standalone-preset.min.js', ], customCssUrl: [ 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-standalone-preset.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui.css', ],

but still it does not load schemas :)))))))))))

UPDATE: using @ApiProperty() solved the issue

Felexonyango commented 8 months ago

adding custom css led me into this image I tried setting headers to app.use((req, res, next) => { res.setHeader("Content-Security-Policy", "default-src 'none'; style-src 'self' https://cdnjs.cloudflare.com"); next(); }); never worked . Any lead?

aryansindhi18 commented 8 months ago

Thanks for your solution, @Milan-960 but it didn't fully solve my issue, all of the request summaries were messed up as you can see here:

image

My solution was similar, but I added custom css to display summaries properly.

// Route-Handler to visit our docs
route.use(
  '/docs',
  swaggerUi.serve,
  swaggerUi.setup(swaggerSpec, {
    customCss:
      '.swagger-ui .opblock .opblock-summary-path-description-wrapper { align-items: center; display: flex; flex-wrap: wrap; gap: 0 10px; padding: 0 10px; width: 100%; }',
    customCssUrl: CSS_URL,
  }),
);

image

I don't think this is the best solution but at least it works... If anyone has a better solution, feel free to share it!

Full code can be found here: https://github.com/DaviidMM/api-auvasa

thanks, was facing the same issue, got resolved using your customCss..!!

shintadev commented 7 months ago

Thanks for your solution, @Milan-960 but it didn't fully solve my issue, all of the request summaries were messed up as you can see here:

image

My solution was similar, but I added custom css to display summaries properly.

// Route-Handler to visit our docs
route.use(
  '/docs',
  swaggerUi.serve,
  swaggerUi.setup(swaggerSpec, {
    customCss:
      '.swagger-ui .opblock .opblock-summary-path-description-wrapper { align-items: center; display: flex; flex-wrap: wrap; gap: 0 10px; padding: 0 10px; width: 100%; }',
    customCssUrl: CSS_URL,
  }),
);

image

I don't think this is the best solution but at least it works... If anyone has a better solution, feel free to share it!

Full code can be found here: https://github.com/DaviidMM/api-auvasa

i think we can do this as well

const file = fs.readFileSync(path.resolve(__dirname, './swagger.yaml'), 'utf8');
const css = fs.readFileSync(
  path.resolve(__dirname, '../node_modules/swagger-ui-dist/swagger-ui.css'),
  'utf8'
);

const swaggerDocument = YAML.parse(file);
const options: swaggerUi.SwaggerUiOptions = {
  customCss: css,
};

app.use(
  '/api-docs',
  express.static('node_modules/swagger-ui-dist'),
  swaggerUi.serve,
  swaggerUi.setup(swaggerDocument, options)
);

i read the origin css file content then use it as customCss, in case other solutions not work for you

YevheniiKyr commented 6 months ago

iss

This time I deployed a nest app and now nothing loads on both android and desktop! I also used customCssUrl... "@nestjs/swagger": "^7.1.17",

image

UPDATE: solved it using : customJs: [ 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-bundle.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-standalone-preset.min.js', ], customCssUrl: [ 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-standalone-preset.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui.css', ],

but still it does not load schemas :)))))))))))

UPDATE: using @ApiProperty() solved the issue

could you provide me with your swagger configuration code?

MOA-CODES commented 6 months ago

Did you try to downgrade your swagger-ui-express dependency to 4.3.0 and also make your swaggerCss variable "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.3.0/swagger-ui.min.css" ?

taiwoajasa245 commented 6 months ago

Hey my problem is that my swaggerUI doesn't show at all. any help?

I deployed using vercel and when I click my link that should take me to my link it doesn't show anything. it just show white page i have tried every other solution said but none worked the browser network showed

swaggerUi-problem

please any help

Noumbissi16 commented 6 months ago

thanks, putting the custom css worked for me

BilalurRehman-27 commented 5 months ago

adding custom css led me into this image I tried setting headers to app.use((req, res, next) => { res.setHeader("Content-Security-Policy", "default-src 'none'; style-src 'self' https://cdnjs.cloudflare.com"); next(); }); never worked . Any lead?

Are you using helmet in your application?

BilalurRehman-27 commented 5 months ago

Hey my problem is that my swaggerUI doesn't show at all. any help?

I deployed using vercel and when I click my link that should take me to my link it doesn't show anything. it just show white page i have tried every other solution said but none worked the browser network showed

swaggerUi-problem

please any help

Are you using helmet in your application? Please see this link if it helps.

abhishek98s commented 5 months ago

// import in index.ts

import pathToSwaggerUi from 'swagger-ui-dist'
app.use(express.static(pathToSwaggerUi.absolutePath()))

and

// for css to load in swagger.ts


const CSS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.3.0/swagger-ui.min.css';
export const swagger = function (app: express.Application) {
  app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerConfig, {
    customCss:
      '.swagger-ui .opblock .opblock-summary-path-description-wrapper { align-items: center; display: flex; flex-wrap: wrap; gap: 0 10px; padding: 0 10px; width: 100%; }',
    customCssUrl: CSS_URL,
  }));
}
vlhsmylv commented 4 months ago

hi there.

I am having an issue with Swagger docs. I could make it work after downgrading the version to 4.3.0. However, now it's not loading my docs.yaml as swagger docs.

This is my swagger util in the express app

import { version } from "../../package.json";
import swaggerJSDoc from "swagger-jsdoc";
import swaggerUi from "swagger-ui-express";
import express from "express";

const options: swaggerJSDoc.Options = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "Test REST API",
      summary: "REST API for Test",
      description: "REST API services for Test",
      version,
    },
    servers: [
      {
        url: "http://localhost:4006/api/v1",
        description: "Local development server",
      }
    ],
    components: {
      securitySchemes: {
        cookieAuth: {
          type: "http",
          in: "bearer",
          name: "JWT",
        },
      },
    },
    security: [
      {
        bearerAuth: [],
      },
    ],
  },
  apis: ["./src/routes/***/**/docs.yaml"],
};

const swaggerSpec = swaggerJSDoc(options);

const swaggerDocsRouter = express.Router();

swaggerDocsRouter.use("/docs", swaggerUi.serve);
swaggerDocsRouter.get(
  "/docs",
  swaggerUi.setup(swaggerSpec, {
    customCssUrl:
      "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.1.0/swagger-ui.min.css",
  })
);

export default swaggerDocsRouter;

I am getting .yaml files from route ["./src/routes/***/**/docs.yaml"]

JoaoVitorJJV commented 4 months ago

olá.

Estou tendo um problema com os documentos do Swagger. Consegui fazê-lo funcionar depois de fazer o downgrade da versão para 4.3.0. No entanto, agora ele não está carregando meus docs.yamldocumentos do Swagger.

Este é o meu utilitário swagger no aplicativo expresso

import { version } from "../../package.json";
import swaggerJSDoc from "swagger-jsdoc";
import swaggerUi from "swagger-ui-express";
import express from "express";

const options: swaggerJSDoc.Options = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "Test REST API",
      summary: "REST API for Test",
      description: "REST API services for Test",
      version,
    },
    servers: [
      {
        url: "http://localhost:4006/api/v1",
        description: "Local development server",
      }
    ],
    components: {
      securitySchemes: {
        cookieAuth: {
          type: "http",
          in: "bearer",
          name: "JWT",
        },
      },
    },
    security: [
      {
        bearerAuth: [],
      },
    ],
  },
  apis: ["./src/routes/***/**/docs.yaml"],
};

const swaggerSpec = swaggerJSDoc(options);

const swaggerDocsRouter = express.Router();

swaggerDocsRouter.use("/docs", swaggerUi.serve);
swaggerDocsRouter.get(
  "/docs",
  swaggerUi.setup(swaggerSpec, {
    customCssUrl:
      "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.1.0/swagger-ui.min.css",
  })
);

export default swaggerDocsRouter;

Estou recebendo .yamlarquivos da rota["./src/routes/***/**/docs.yaml"]

Same thing here. I added the custom CSS to Vercel and it worked, but it doesn't load the YAML files

import express from 'express';
import cors from 'cors';
import 'dotenv/config';
import router from './src/rotas';
import swaggerUi from 'swagger-ui-express';
import swaggerJSDoc from 'swagger-jsdoc';

const app = express();
const port = process.env.PORT || 3000;

app.use(cors());
app.use(express.json());
app.use('/api', router);

// Swagger Configuração
const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'API - Flex Test',
      version: '1.0.0',
      description: 'Documentação com Swagger'
    },
  },
  apis: ['/src/docs/swagger/**/*.yaml']
}

const swaggerSpec = swaggerJSDoc(options);
const CSS_URL = "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.1.0/swagger-ui.min.css"

app.use('/api-swagger', swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
  customCss:
    '.swagger-ui .opblock .opblock-summary-path-description-wrapper { align-items: center; display: flex; flex-wrap: wrap; gap: 0 10px; padding: 0 10px; width: 100%; }',
  customCssUrl: CSS_URL,
}));

// Start server
app.listen(port, () => {
  console.log(`Servidor rodando na porta ${port}`);
});

export default app;

image

JoaoVitorJJV commented 4 months ago

Update: I managed to get it to work, but not the way I wanted. It looks like you need to use __dirname.

And even then, it only loaded once yaml file. I had to centralize all documentation in this file.


import swaggerJSDoc from "swagger-jsdoc";

// You need to use this, even if you don't attribute it to anything
const yamlFiles = [`${__dirname}/docs/swagger/swagger.yaml`]

const options = {
    definition: {
        openapi: '3.0.0',
        info: {
            title: 'API - Flex Test',
            version: '1.0.0',
            description: 'Documentação com Swagger'
        },
    },
    apis: ['./docs/swagger/swagger.yaml']
}

const swaggerSpec = swaggerJSDoc(options);

export default swaggerSpec;

I dont use the variable yamlFiles, but without it vercel doesn't find any files

MD-SanjayKumar commented 4 months ago
const yamlFiles = [`${__dirname}/docs/swagger/swagger.yaml`]

Using this also I'm not able to get specs, can you help me with a some solutions?

26kito commented 3 months ago
const css = fs.readFileSync(
  path.resolve(__dirname, '../node_modules/swagger-ui-dist/swagger-ui.css'),
  'utf8'
);

I have already try this but it still doesn't work for me

Phantom-KNA commented 3 months ago

I find the problem, because Vercel block cloudfare css styles from Swagger, this work for me:

import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
app.use('/public', express.static(path.join(__dirname, 'public')));

app.use((req, res, next) => {
  if (req.url === '/public/theme-material.css') {
    res.sendFile(path.join(__dirname, 'public') + '/css/theme-material.css');
  }
   else if (req.url === '/api-docs/swagger-ui.css') {
    res.sendFile(path.join(__dirname, 'public') + '/css/swagger-ui.css');
  }
  else {
    next();
  }
});

app.use(
  "/api-docs",
  swaggerUI.serve,
  swaggerUI.setup(specs, {
    customCssUrl:
      "/public/theme-material.css"
  })
);

Create folder public and one folder inside, css. After that put your custom.css style and swagger-ui.css

swagger-ui.zip

DmitriyUshkvarok commented 2 months ago

NestJS was helped by the following solution: I created a public folder at the root of the project, then inside the public folder, I created css and js folders. I copied the file from the Swagger modules to the css folder (swagger-ui.css), and moved the files swagger-ui-bundle.js and swagger-ui-standalone-preset.js to the js folder.

Next, I installed the @nestjs/serve-static library and added the following configuration to the AppModule: ServeStaticModule.forRoot({ rootPath: join(__dirname, '..', 'public'), serveRoot: '/public', }),

In the Swagger configuration, I added custom paths: SwaggerModule.setup('api', app, document, { customCssUrl: '/public/css/swagger-ui.css', customJs: [ '/public/js/swagger-ui-bundle.js', '/public/js/swagger-ui-standalone-preset.js', ], });

Everything works in all browsers! The styles are applied correctly, and the schemas are displayed.

mcnaveen commented 2 months ago

Nothing seems to be working. I only see a blank page.

Am I doing something wrong?

Project Repo: https://github.com/mcnaveen/Random-Words-API Deployment URL: https://random-words-api.vercel.app/

Swagger error vercel

kyleysrael commented 2 months ago

NestJS was helped by the following solution: I created a public folder at the root of the project, then inside the public folder, I created css and js folders. I copied the file from the Swagger modules to the css folder (swagger-ui.css), and moved the files swagger-ui-bundle.js and swagger-ui-standalone-preset.js to the js folder.

Next, I installed the @nestjs/serve-static library and added the following configuration to the AppModule: ServeStaticModule.forRoot({ rootPath: join(__dirname, '..', 'public'), serveRoot: '/public', }),

In the Swagger configuration, I added custom paths: SwaggerModule.setup('api', app, document, { customCssUrl: '/public/css/swagger-ui.css', customJs: [ '/public/js/swagger-ui-bundle.js', '/public/js/swagger-ui-standalone-preset.js', ], });

Everything works in all browsers! The styles are applied correctly, and the schemas are displayed.

Hello can I see your implementation?