1

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);
C-RAD
  • 1,052
  • 9
  • 18
  • Is this a CORS request? – JBaczuk Sep 16 '21 at 15:30
  • @JBaczuk no it is not. – C-RAD Sep 16 '21 at 15:33
  • @pzaenger That did not change anything, it is still not set. – C-RAD Sep 16 '21 at 15:33
  • 1
    Just tested your code and it does return the headers (looking at the response headers in chrome inspector). I created an HTML file for it to serve up, and visited HTTP://localhost:8080. EDIT: But it doesn't serve the object-src, script-scr, and style-src headers. – JBaczuk Sep 16 '21 at 15:38
  • Ooops those aren't headers... – JBaczuk Sep 16 '21 at 15:45
  • @JBaczuk That's how I was testing, you made me realize this file isn't used in my dev env though...but also my production env did not like the syntax I was using for multi-line strings. – C-RAD Sep 16 '21 at 15:50

1 Answers1

1

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();
});
JBaczuk
  • 13,886
  • 10
  • 58
  • 86