nonce vs hash
Both nonce and hash let you keep CSP strict while still allowing specific inline code. The difference is how stable that code is and where the policy is generated.
Use nonce when content is dynamic
A nonce is generated fresh for each response and added to both the CSP header and the allowed inline tag.
Content-Security-Policy: script-src 'nonce-abc123'
<script nonce="abc123">...</script>
Use hash when content is fixed
A hash works well when the inline snippet does not change often and can be calculated ahead of time.
Content-Security-Policy: script-src 'sha256-abc...'
Quick rule of thumb
- Dynamic rendering: prefer nonce.
- Static build output: prefer hash.
- Frequently changing inline code: nonce is easier to maintain.
- CDN-cached static HTML: hash is often simpler.