How to set headers for a React app created using 'create-react-app' How to set headers for a React app created using 'create-react-app' reactjs reactjs

How to set headers for a React app created using 'create-react-app'


Simply modifying index.html as you have is not sufficient, at least for X-Frame-Options. Per OWASP:

Common Defense Mistakes

Meta-tags that attempt to apply the X-Frame-Options directive DO NOT WORK. For example, ) will not work. You must apply the X-FRAME-OPTIONS directive as HTTP Response Header...

MDC has a similar warning.

I spent some time looking, but didn't find a way to set X-Frame-Options in React itself. There are ways to do it at the server level or in other languages (e.g. for Tomact, or in Java, or with webpack, or configure it with Spring Security), which may or may not be helpful to you.

React doesn't seem to support Content-Security-Policy either... at least not as of 2013, and I searched but did not find any more recent change in position.


You have to override some webpack config that comes with create-react-app and add "X-Frame-Options": "SAMEORIGIN".

But in CRA, you can't do that directly with a webpack.config.js. You gotta use a package that rewires the way CRA start / build your app. Here are the rewiring packages you can use:

  • react-app-rewired (CRA v1)
  • customize-cra or rescript (CRA v2)
  • craco (CRA v3)

To know which CRA version you used, you can roughly follow the react-scripts version in your package.json.

craco

I succeeded with this craco config!!! In craco.config.js:

module.exports = {    webpack: {        headers: {            'X-Frame-Options': 'Deny'        }    }}

(I tested by scanning in Burpsuite; the Frameable Response issue was gone.)

Reference: How to set alias path via webpack in CRA (create-react-app) and craco?

react-app-rewired

I THINK you could try this, BUT I haven't tested it. In config-overrides.js:

module.exports = {    devServer: function(configFunction) {        return function(proxy, allowedHost) {            const config = configFunction(proxy, allowedHost)            config.headers = {                'X-Frame-Options': 'Deny'            }            return config        }    }}

Reference: Create React App adding CORS header

*I may have loosely gotten the versions wrongly, please correct if so.


If you are talking specifically for the dev server, you can configure the underlying express instance using the 'manually configure proxy' process.

You can set headers there:

// src/setupProxy.jsmodule.exports = function(app) {  app.use((req, res, next) => {    res.set({        'foo': 'bar'    });      next();  }); };