Web hardeningCSP

Content Security Policy (CSP)

A Content Security Policy is an HTTP header that declares which sources a page may load scripts, styles and other resources from.

Updated 2 Sept 2026

In more detail

CSP is the most effective single mitigation against injected third-party scripts: a script tag pointing at an origin the policy does not allow is blocked by the browser even though the injection itself succeeded. Modern policies are built around nonces or hashes for inline scripts plus strict-dynamic, rather than long allowlists of hostnames, because allowlists tend to include origins that can serve arbitrary code.

Why Content Security Policy (CSP) matters

On a content site, CSP is what stops an injected analytics-lookalike script from exfiltrating form data. It also turns silent injections into visible signals: violation reports arrive as soon as blocked content is requested, which is often the first indication of a compromise.

How it works

The browser evaluates each resource request against the policy's directives (default-src, script-src, style-src, connect-src, frame-ancestors and others) and blocks non-matching requests. Content-Security-Policy-Report-Only applies the same evaluation without blocking, so a policy can be tuned against real traffic before enforcement, with violations posted to a report endpoint.

Examples

  • script-src 'nonce-r4nd0m' 'strict-dynamic' — only scripts carrying the per-response nonce execute.
  • connect-src 'self' https://api.example.com — blocks exfiltration to an attacker-controlled endpoint.
  • frame-ancestors 'none' — prevents the page being framed, replacing X-Frame-Options.

How it is detected or measured

Deploy in report-only mode first and review the violation reports; the browser console lists every blocked resource with the directive that blocked it.

Frequently asked questions

Does CSP replace fixing cross-site scripting?
No. CSP limits the damage of an injection that already happened. Input validation, output encoding and framework escaping remain the primary fix.

Where this matters

  • Security Headers Explained

    What each HTTP security header protects against, sensible starting values, and the order to deploy them without breaking your site.

Related tools

Sources

Related terms