Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js helmet and swagger-ui

I am using a swagger for API documentation in Node.js. Now I want to use helmet for security, but when I am using helmet, error occur. However, if I place the helmet below the router for swagger, then it works fine, which means helmet do something that makes swagger-ui not be loaded.

Below code is how I used helmet.

var helmet = require('helmet')
app.use(helmet());

Below image is the error from swagger

enter image description here

Fix to allow cors but still got an error.

//allow cors
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });
  
// use helmet
var helmet = require('helmet')
app.use(helmet());
like image 620
yongseung Avatar asked Nov 08 '25 08:11

yongseung


1 Answers

Always make sure to render the Swagger UI template before setting up the HelmetJS middleware to avoid issues.

// before
const document = SwaggerModule.createDocument(app, new DocumentBuilder().build());
SwaggerModule.setup('docs', app, document);

// then
app.use(helmet());

resource

like image 108
Fedenko Maksym Avatar answered Nov 10 '25 08:11

Fedenko Maksym



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!