Search code examples
reactjswebpackgatsbycontent-security-policygatsby-plugin

Gatsby Content-Security-Policy


I created a new gatsby project using the default starter. All I have done after creating the project is npm install gatsby-plugin-csp plugin and added configurations in gatsby-config.js like so:

{
  resolve: `gatsby-plugin-csp`,
  options: {
    disableOnDev: false,
    reportOnly: false, // Changes header to Content-Security-Policy-Report-Only for csp testing purposes
    mergeScriptHashes: false, // you can disable scripts sha256 hashes
    mergeStyleHashes: false, // you can disable styles sha256 hashes
    mergeDefaultDirectives: true,
    directives: {
      "script-src": "'self' 'unsafe-inline' www.google-analytics.com",
      "style-src": "'self' 'unsafe-inline'",
      "img-src": "'self' data: www.google-analytics.com"
    }
  }
},

However when I run npm run develop and load localhost:8000 I get hit with the following error in the console along with a blank, white page:

Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' www.google-analytics.com".

at Object../node_modules/@pmmmwh/react-refresh-webpack-plugin/client/ReactRefreshEntry.js

(commons.js:404) at Object.options.factory (commons.js:4439) at webpack_require (commons.js:3811) at commons.js:5147 at Function.webpack_require.O (commons.js:3860) at commons.js:5150 at commons.js:5152

When I add 'unsafe-eval' to the script-src, the page loads just fine however that is of course unsafe.

What configuration change do I need to make to allow for the page to load without using 'unsafe-eval' or even 'unsafe-inline' if possible?


Solution

  • I read this error that the react-refresh-webpack-plugin is unable to function because of the CSP. react-refresh-webpack-plugin is used only during development.

    Your best bet is to just set disableOnDev: true in gatsby-plugin-csp's options. It's self-explanatory but this will just disable the CSP in development ($ gatsby develop). To test the CSP locally just do $ gatsby build and $ gatsby serve.