node.jsexpressvercel

CORS issue when I try to request from the Swagger UI on Vercel


When I try to run an endpoint on Swagger UI I have always the same issue :

Failed to fetch.
Possible Reasons:

CORS
Network Failure
URL scheme must be "http" or "https" for CORS request.

I code an API in express.js

// Swagger definition
const swaggerDefinition = {
  swagger: "2.0",
  info: {
    version: "1.0.0",
    title: "API",
    description: "API Documentation for fetching data"
  },
  host: "localhost:3000",
  schemes: ["http"]
};

// Options for the swagger docs
const options = {
  swaggerDefinition,
  apis: ["./api/index.js"], // Update with actual path to the API file
};

// Initialize swagger-jsdoc
const swaggerSpec = swaggerJsdoc(options);

const CSS_URL = "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.1.0/swagger-ui.min.css"


// Then pass these options to cors:
app.use(cors(options));

// Serve swagger docs
app.use('/api-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,
}));

And I added a vercel.json file too but I can't understand why I have always the same issue :

{
  "version": 2,
  "builds": [
    { "src": "api/*.js", "use": "@vercel/node" }
  ],
  "routes": [
    { "src": "/(.*)", "dest": "/api/index.js" }
  ],
  "headers": [
    {
      "source": "/api/index.js",
      "headers": [
        { "key": "Access-Control-Allow-Credentials", "value": "true" },
        { "key": "Access-Control-Allow-Origin", "value": "*" },
        { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
        { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }
      ]
    }
  ]
}

I have no this issue with another deployment service like Heroku. This error happened only when I try to push on Vercel.


Solution

  • Use definition ✅ property not swaggerDefinition

    So your options would be

    const options = {
      definition : swaggerDefinition,
      apis: ["./api/index.js"]
    };
    
    // Initialize swagger-jsdoc
    const swaggerSpec = swaggerJsdoc(options);