6
votes

Webpack has a feature of adding nonce to all scripts it loads.

To activate the feature set a __webpack_nonce__ variable needs to be included in your entry script.

Entry file in react app geneated by create react app by defaulty is index.js. So all I need to do is add in entry file:

 // ...
__webpack_nonce__ = 'c29tZSBjb29sIHN0cmluZyB3aWxsIHBvcCB1cCAxMjM=';
// ...

And last thing is to enable webpack CSP.

Please note that CSPs are not enabled by default. A corresponding header Content-Security-Policy or meta tag needs to be sent with the document to instruct the browser to enable the CSP. Here's an example of what a CSP header including a CDN white-listed URL might look like: Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com;

However, I got error

'__webpack_nonce__' is not defined

I've tried to declare nonce. Still doesn't work.

webpack_nonce is specified in the entry file and not in the configuration.

So, what I am doing wrong? Maybe docs are missing some key info about that topic? How to enable CSP feature in webpack for React app?

1
So you have added the CSP meta tag in your html file?hazardous
check that this is the real entry point and not some file that other entry point (in cra) that consumes it.felixmosh
Tagged this to Sean Larkin from webpack on Twitter, hope he takes a look.hazardous
@leepowell nopeogostos
i'm also trying to follow article at webpack.js.org/guides/csp and it seems to be missing detailed implementation details, the 'further reading' section content is verbose, and the stackoverflow link shows a different nonce implementation method, which i have tried but doesn't work. The source list for Content Security Policy directive 'script-src' contains an invalid source: ''******''. It will be ignored. and it is also refuses to load webpack's outputted bundle.js (which should contain the nonce as this was included in the entry file: __webpack_nonce__ = '******')user1063287

1 Answers

-6
votes

If you are using create-react-app then it may be ESLint that is reporting the error.

Try disabling it for the line:

__webpack_nonce__ = 'c29tZSBjb29sIHN0cmluZyB3aWxsIHBvcCB1cCAxMjM='; // eslint-disable-line no-undef