Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Browser and Web APIs

Content Security Policy (CSP)

Concept page on Content Security Policy: how the header or meta tag limits scripts, styles and connections, nonces, violation events and a safe rollout.

Content Security Policy is a browser feature that limits what a page is allowed to load and run. You declare a policy, and the browser refuses anything that does not match it: a script from an unknown host, an inline <script>, an eval() call, a connection to an unexpected server. Its main job is to turn many cross-site scripting (XSS) bugs from "attacker code runs" into "browser blocks it and reports it".

CSP is a second line of defense. It does not replace escaping output and validating input; it limits the damage when something slips through.

Setting a policy

The usual way is an HTTP response header:

HTTP
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; img-src 'self' data:

A policy is a list of directives separated by semicolons. Each directive names a resource type and a list of allowed sources.

Directive Controls
default-src Fallback for any resource type without its own directive.
script-src JavaScript sources, inline scripts, eval().
style-src Stylesheets and inline styles.
img-src, font-src, media-src Images, fonts, audio and video.
connect-src fetch(), XMLHttpRequest, WebSocket and EventSource targets.
frame-src, frame-ancestors Which pages you may embed, and who may embed you.
object-src Plugins; usually set to 'none'.
base-uri, form-action Where <base> may point and where forms may post.

Common source values: 'self' (same origin), 'none', a host such as https://cdn.example.com, a scheme such as https: or data:, 'nonce-...', 'sha256-...', and 'strict-dynamic'. The quotes around keywords are part of the syntax.

You can also use <meta http-equiv="Content-Security-Policy" content="..."> in the page head. It applies only to content that comes after it, and some directives (such as frame-ancestors) work only in the header.

Nonces and hashes

Inline scripts are the usual XSS payload, so a strict policy blocks them. To allow your own, the server generates a fresh random nonce for every response, puts it in the header ('nonce-abc') and in each trusted tag (<script nonce="abc">). An attacker who injects markup cannot guess it. A hash ('sha256-...') allows one specific inline script by its content.

A nonce lets one script run

The second script has no nonce, so the browser refuses to run it, and a violation is reported. The eval() call is blocked too, because script-src without unsafe-eval forbids evaluating strings as code.

Report-only mode and rollout

Add a policy under Content-Security-Policy-Report-Only first. The browser enforces nothing but fires violation events and, with report-to (or the older report-uri), sends reports to an endpoint you choose. Watch the reports, fix legitimate violations, then switch to enforcing.

You can also listen in the page itself, as the example does: a securitypolicyviolation event on document carries blockedURI, violatedDirective, effectiveDirective and sourceFile.

JS Reading violation details

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Usage notes

  • Start strict, loosen consciously. 'unsafe-inline' and 'unsafe-eval' cancel much of the protection; avoid them in script-src.
  • Prefer nonces or hashes over host allow-lists for scripts; allow-lists tend to include hosts that can serve attacker-controlled code.
  • Inline event handlers (onclick="...") and javascript: URLs are blocked by strict policies; use addEventListener().
  • Inline styles are governed by style-src; many sites keep 'unsafe-inline' there longer than for scripts, which is a smaller (but real) risk.
  • A policy can break extensions and third-party widgets. Test with the browser console open; violations are logged there.
  • Multiple policies combine. When several are present, a resource must satisfy all of them.
  • frame-ancestors replaces the older X-Frame-Options for preventing clickjacking.
  • Trusted Types is a related, newer mechanism that guards dangerous DOM sinks such as innerHTML; check support before relying on it.

Browser support

CSP is supported in all current browsers. Some newer features ('strict-dynamic' handling details, report-to, Trusted Types) differ by browser, so check a compatibility table.