Course contentsShow
← Web Development
Lesson 2859 of 2,98251. Content Security PolicyFree lesson

Understanding CSP Hashes

Learn what CSP hashes are and how they allow static inline code without dynamic nonces.

Understanding CSP Hashes

You'll learn: How CSP hashes let you approve specific inline scripts or styles without generating a new nonce on every page load.

What Are CSP Hashes?

While nonces change with every request, CSP hashes provide a way to whitelist specific, unchanging inline code by calculating a cryptographic hash of its exact content. Think of it like a fingerprint: if the inline script or style matches the hash you've declared in your CSP header, the browser allows it to execute.

How Hashes Work

When you have static inline code that never changes (like critical CSS or a tiny analytics snippet), you can:

  1. Calculate a SHA-256, SHA-384, or SHA-512 hash of the exact code content
  2. Add that hash to your script-src or style-src directive
  3. The browser compares the inline code's hash against your whitelist

Example CSP header:

Content-Security-Policy: script-src 'sha256-abc123...'; style-src 'sha256-def456...'

If your inline <script> tag's content produces the hash sha256-abc123..., it runs. If even one character differs, the hash won't match and the code is blocked.

When to Use Hashes vs Nonces

  • Hashes: Perfect for static content that never changes (critical CSS, fixed analytics code)
  • Nonces: Better for dynamically generated pages where content varies per request

Hashes eliminate the need for server-side nonce generation when your inline code is truly static—you can calculate the hash once during build time and embed it in your CSP policy.

Key Takeaway: CSP hashes whitelist specific inline code by its exact content fingerprint, ideal for static scripts and styles that don't require dynamic nonces.