Content Security Policy (CSP)
Examples


CSP Inline Scripts

When you enable CSP, it will block inline scripts, but there are some ways that you can allow inline scripts and still use Content Security Policy.

Allow Inline Scripts using a Nonce

One of the easiest ways to allow inline scripts when using CSP is to use a nonce. A nonce is just a random, single use string value that you add to your Content-Security-Policy header, like so:

script-src js-cdn.example.com 'nonce-r@nd0m';

Assuming our nonce value is r@nd0m (you need to randomly generate a new nonce for every HTTP request), we can now use an inline script tag like this:

<script nonce="r@nd0m">
	doSomething();
</script>

Allow Inline Scripts using a Hash

A second approach to allow inline scripts is to use a hash, with this approach you compute the hash of your JavaScript code, and put the value in our CSP policy:

script-src js-cdn.example.com 'sha256-xzi4zkCjuC8lZcD2UmnqDG0vurmq12W/XKM5Vd0+MlQ='
Tip: your browser developer tools console might compute the hash for you and output it in the console when inline scripts are blocked by CSP.

Other methods

The unsafe-inline source list value can be used to allow inline scripts, but this also defeats much of the purpose of CSP.

CSP Level 3 (newest browsers) support a source list value: unsafe-hashes which can be used to allow inline script in javascript event handlers (eg onclick or onmouseover, etc).