Search code examples
javascriptnode.jsswaggerswagger-ui

Getting empty paths key in swagger when deployed. Local is working


I am using swagger-jsdoc. Everything seems fine and I am getting the json till I am using localhost, when I use live url, it's giving me nothing in the paths keys ie.

{
    "info": {
        "title": "App API",
        "version":"0.0.0",
        "description":"Server API documentation"
    },
    "host":"something.com",
    "basePath":"/",
    "schemes":["https"],
    "swagger":"2.0",
    "paths":{},
    "definitions":{},
    "responses":{},
    "parameters":{},
    "securityDefinitions":{},
    "tags":[]
}

This is what I am getting on live. The same code is working on localhost/swagger.json, but not with https://something.com/swagger.json

var swaggerJSDoc = require('swagger-jsdoc');

var swaggerOptions = {
    swaggerDefinition: config.swaggerDefinition || {
        info: { // API informations (required)
            title: 'Hello World', // Title (required)
            version: '1.0.0', // Version (required)
            description: 'A sample API', // Description (optional)
        },
        host: 'localhost:3000', // Host (optional)
        basePath: '/', // Base path (optional)
    },
    apis: ['./routes/*.js'], // Path to the API docs
};

var swaggerSpec = swaggerJSDoc(swaggerOptions);

router.get('/swagger.json', function(req, res) {
  res.setHeader('Content-Type', 'application/json');
  res.send(swaggerSpec);
});

Solution

  • This problem arose due to the path of the routes.

    I was using apis: [ './routes/*.js' ]

    But my server was having path ./bin/www so in these cases ./routes won't work at all, the best way while implementing this would be to use __dirname instead. eg.

    apis: [`${__dirname}/routes/*.js`]
    

    I have solved it the same day but forgot to add an answer here.