← Lessons

quiz vs the machine

Gold1380

Frontend

Content Security Policy Deep

A response header that whitelists allowed sources and blocks injected scripts even when XSS slips through.

6 min read · core · beat Gold to climb

What it is

A Content Security Policy is an HTTP response header that tells the browser which sources of scripts, styles, images, and connections are allowed. It is a defense in depth layer against injection.

Key directives

  • default src sets the fallback policy for most resource types.
  • script src controls where JavaScript may load from and whether inline scripts run.
  • connect src limits fetch, XHR, and WebSocket targets.
  • frame ancestors controls who may embed your page.

Nonces and hashes

Allowing all inline scripts defeats the policy. Instead use a per response nonce or a hash of the script body. Only scripts carrying the matching nonce execute, so an injected inline script is blocked.

Strict CSP pattern

A modern strict policy uses strict dynamic with a nonce. Trust flows from the nonced script to any scripts it loads, which lets you drop fragile host allowlists.

Reporting

Use report only mode to collect violations without breaking the page, then enforce once clean.

Key idea

CSP whitelists trusted sources and uses nonces or hashes so injected scripts are blocked even when XSS exists.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a CSP nonce accomplish?

2. Which mode collects violations without breaking the page?

3. Which directive controls who can embed your page?