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

Nonces vs Hashes: When to Use Each

Compare nonces and hashes, understanding trade-offs between dynamic and static approaches.

Nonces vs Hashes: When to Use Each

You'll learn when to choose nonces versus hashes for your Content Security Policy inline script strategy.

Both nonces and hashes allow you to whitelist specific inline scripts while keeping a strict CSP, but they serve different use cases based on whether your content is dynamic or static.

The Core Trade-off

Nonces are like unique, single-use tickets generated fresh on every page load. They're perfect for dynamic content where your server renders different HTML for each request. Since each nonce is random and changes constantly, even if an attacker injects a script, they can't predict the current valid nonce.

Hashes are like fingerprints of exact script content. They work best for static inline scripts that never change. Once you calculate a hash, it stays valid as long as the script content remains identical—even a single space or newline will break the hash.

When to Choose Each

Use nonces when:

  • You have server-side rendering that generates pages dynamically
  • You're using a templating engine that can inject unique values
  • Your inline scripts contain dynamic data or user-specific content
  • You want simpler maintenance (one nonce per page, not per script)

Use hashes when:

  • You have truly static sites or single-page applications
  • Your inline scripts never change (common for build-time injected code)
  • You don't have server-side rendering capabilities
  • You're working with third-party scripts you trust but can't modify

Think of it like this: nonces are actively managed security guards checking fresh credentials, while hashes are pre-approved signatures on documents.

Key Takeaway: Choose nonces for dynamic, server-rendered content where you can generate fresh values per request; choose hashes for static, unchanging inline scripts where simplicity and build-time generation work better.