Architecture · Guides
How to allow one inline script under a strict Content Security Policy.
A dark mode toggle needs an inline script that runs before first paint. Instead of unsafe-inline, allow-list its SHA-256 hash in your CSP.
Key takeaways
- A theme script has to run before first paint to avoid a flash of the wrong theme, so it must be inline.
script-src 'self'blocks inline scripts. Adding'unsafe-inline'would fix it but weakens the policy.- A SHA-256 hash in
script-srcallows exactly one script and nothing else. - Any change to the script, even a space, breaks the hash and the browser blocks it silently.
The flash problem
A dark and light theme switch has a classic bug. If the saved preference is applied from an external script that loads after the page begins to render, a visitor who chose light mode sees a flash of dark first. It is small, but it looks broken.
The cure is a tiny script in the <head> that reads the saved preference from localStorage and sets a data-theme attribute immediately, before the browser paints. For it to run early, it has to be inline, not a separate file:
<script>(function(){try{var t=localStorage.getItem('theme');if(t==='light'||t==='dark'){document.documentElement.setAttribute('data-theme',t);}}catch(e){}})();</script>
The conflict with CSP
My site sends a strict Content Security Policy, including script-src 'self'. That tells the browser to run scripts only from my own origin, which blocks inline scripts as a defence against injected code. So the theme script is blocked.
Why not just allow inline scripts
The shortcut is 'unsafe-inline' in script-src. It makes the toggle work, and it also lets any injected script run, which removes much of what CSP is for. I did not want to weaken the protection for the whole site just to run twelve lines.
The better way: a hash
CSP lets you allow a specific inline script by listing the SHA-256 hash of its exact contents. The browser hashes each inline script it finds and runs it only if the hash is on the list. Any other inline script, such as one injected by an attacker, has a different hash and is blocked.
Because my theme script is byte-identical on every page, one hash covers the whole site.
Computing the hash
Hash the script's contents, with no <script> tags:
printf '%s' '(function(){...})();' | openssl dgst -sha256 -binary | openssl base64
Then add it to the header:
script-src 'self' 'sha256-<the-base64-hash>';
You can also open the browser console: when a script is blocked, Chrome and Firefox print the hash they computed, which you can copy.
The catch
If the script changes by a single character, the hash no longer matches and the browser silently blocks it. There may be no visible error on the page, only a console message. The symptom is that the theme flash returns, or the toggle stops applying a saved choice.
For that reason I keep a comment next to the CSP line in the Nginx config with the command to recompute the hash, and I treat that script as frozen. If I must change it, I update the hash in the same deploy.
Other options
- Nonces: a random value per response, added to the script tag and the header. Good for dynamic sites, but a static file cannot change per request without server support.
- External script with
defer: simplest and compatible with CSP, but reintroduces the flash. - CSS-only approach with
prefers-color-scheme: works for the system theme but cannot remember a manual choice.
For a static site where the script never changes, the hash is the cleanest choice.
A short checklist
- Keep the inline script minimal and identical on every page.
- Compute its SHA-256 hash.
- Add the hash to
script-srcand leave out'unsafe-inline'. - Test with the browser console open on each page type.
- Document how to recompute the hash.
Frequently asked questions
Does CSP hash allow-listing work for inline event handlers?
Not by default. Inline handlers like onclick need 'unsafe-hashes' too, which is another reason to avoid them.
Can attackers reuse my hash?
Only by injecting a script with exactly the same content, which would be your own theme script, not something harmful.
Does this affect SEO?
Not directly. A good CSP is a security measure, but a broken one that blocks needed scripts can harm user experience, so test carefully.
Want a site that scores well and stays locked down?
Get in touch