Content Security Policy
01 / 02

CSP Fundamentals: Directives, self & Blocking Inline Scripts

Content Security Policy: Directives, self & Blocking Inline Scripts

A Content Security Policy lets a site declare an allowlist of trusted sources for scripts, styles, images, and other resources -- primarily to mitigate cross-site scripting (XSS) by blocking the browser from executing unauthorized content, even if injected.

Delivering the Policy

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; object-src 'none'

# The HTTP header is the most common, robust delivery method
# (a <meta http-equiv> tag is also possible but more limited)

'self' and default-src

'self' means the page's own origin (scheme+host+port). default-src is a catch-all fallback for any directive not explicitly set -- if script-src isn't specified, the browser falls back to default-src's value.

Why Inline Scripts Get Blocked

A core XSS-defense benefit of CSP comes from blocking inline <script> blocks by default. Allowing 'unsafe-inline' removes that protection -- an attacker's injected inline script would then also be permitted to run.

Nonces: Permitting Specific Inline Scripts

<!-- Header: script-src 'nonce-r4nd0m123' -->
<script nonce="r4nd0m123">
  console.log("trusted, matches the header's nonce");
</script>

<!-- A fresh nonce is generated per page load -- an attacker
     injecting a script can't guess the correct value, so
     their script gets blocked while this trusted one runs -->

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free