Home > Blockchain >  Can't Add Headers Using Express.js
Can't Add Headers Using Express.js

Time:09-17

I have an Express app that serves a some static files. I was able to add the Strict-Transport-Security header but when I try to add more headers, (X-Frame-Options and Content-Security-Policy) Express does not add them to the response.

I am using Express 4.17.1 and my server.js is below.

const express = require('express');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();

if (process.env.NODE_ENV !== "development") {
  app.use(function(req, res, next) {
    res.setHeader('Strict-Transport-Security', 'max-age=63072000; includeSubDomains; preload');

    next();
  });
}

app.use(function(req, res, next) {
  res.setHeader('X-Frame-Options', 'DENY');
  res.setHeader('Content-Security-Policy', "frame-src 'none'; " \
    "object-src 'none'; " \
    "script-src 'self'; " \
    "style-src 'self' "
  );

  next();
});

app.use('/dist', express.static(path.join(__dirname, 'dist')));

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'dist/index.html'));
});

app.listen(port);

CodePudding user response:

Using \ for newlines is not valid syntax. You can replace them with or combine the values for the Content-Security-Policy header into one string using backticks, for example.

The rest of the headers work, just keep in mind that you can only use res.setHeader for one header at a time. See https://stackoverflow.com/a/40841390/3499115

app.use(function(req, res, next) {
  res.setHeader('X-Frame-Options', 'DENY');
  res.setHeader('Content-Security-Policy', `frame-src 'none'; object-src 'none'; script-src 'self'; style-src 'self';`);

  next();
});
  • Related