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

Adding Hashes to CSP Headers

Learn the syntax for including script and style hashes in Content-Security-Policy headers.

Adding Hashes to CSP Headers

You'll learn how to write the correct syntax for including script and style hashes in your Content-Security-Policy headers.

The Core Idea

Now that you can generate SHA-256 hashes for your inline scripts and styles, you need to tell the browser to trust them. You do this by adding those hashes directly to your CSP header using specific syntax. Think of it like giving the bouncer at a club a VIP list—each hash is a unique ID that grants access to one specific piece of code.

The Syntax

For inline scripts, add the hash to your script-src directive using the format 'sha256-[hash]' (note the single quotes):

Content-Security-Policy: script-src 'self' 'sha256-abc123...xyz'

For inline styles, use the same pattern in your style-src directive:

Content-Security-Policy: style-src 'self' 'sha256-def456...uvw'

Multiple Hashes

If you have several inline scripts or styles, simply space-separate multiple hashes:

Content-Security-Policy: script-src 'self' 'sha256-hash1' 'sha256-hash2'; style-src 'self' 'sha256-hash3'

Important Details

  • Always wrap each hash in single quotes
  • The prefix sha256- must be lowercase
  • The hash itself is base64-encoded (from your hash generation step)
  • Each hash authorizes exactly one inline block—change even a space, and the hash becomes invalid

Key Takeaway: Add CSP hashes to headers using the format 'sha256-[base64hash]' in the appropriate directive, with single quotes and space-separated for multiple values.