Skip to content

Content Security Policy Deep Dive

Implement and debug Content Security Policy headers to prevent XSS and data injection attacks.

What you'll learn

  • CSP directives: default-src, script-src, style-src, img-src
  • nonce and hash sources for inline scripts
  • Reporting mode with Report-Only header
  • CSP strict-dynamic and trusted types

Concept

Content Security Policy Deep Dive

Content Security Policy (CSP) is an HTTP header that restricts what resources the browser can load, the most powerful defense against XSS.

Directives

default-src is fallback for all types. script-src controls JS sources: 'self', specific URLs. style-src controls CSS. connect-src controls XHR/fetch/WebSocket. Start with default-src 'self'.

Nonce and Hash

To allow inline scripts without 'unsafe-inline', use a nonce: random string per request in script tag and CSP header. Alternatively, use hash of script content. Nonces preferred for dynamic scripts.

Report-Only Mode

Content-Security-Policy-Report-Only tests CSP without blocking. Browser sends violation reports but doesn't block. Use to roll out CSP safely: test, fix, then enforce.

strict-dynamic and Trusted Types

strict-dynamic trusts nonce-loaded scripts to load others. Trusted Types requires all sink assignments (innerHTML, eval) to go through sanitization policy. Strongest XSS defense.

Example

              const policies = {
  basic: "default-src 'self';",
  withCDN: "default-src 'self'; script-src 'self' https://cdn.example.com;",
  withNonce: (n) => `default-src 'self'; script-src 'self' 'nonce-${n}';`,
  strict: (n) => `default-src 'self'; script-src 'nonce-${n}' 'strict-dynamic'; connect-src 'self';`,
  report: "default-src 'self'; report-uri /csp-report;"
};
function genNonce() { const a = new Uint8Array(16); crypto.getRandomValues(a); return btoa(String.fromCharCode(...a)); }
const nonce = genNonce();
console.log('Nonce:', nonce.substring(0, 16) + '...');
console.log('Strict CSP:', policies.strict(nonce));
document.addEventListener('securitypolicyviolation', e => console.log('Violation:', e.violatedDirective, e.blockedURI));
            

policies defines CSP configurations. genNonce creates per-request random nonce. strict policy uses strict-dynamic. Violation handler logs blocked resources.

Try it

  • Hash Generator

    CSP nonces use cryptographic randomness - see how secure nonces are generated.

Common mistakes

The mistake

Using 'unsafe-inline' in script-src.

The fix

unsafe-inline defeats CSP's XSS protection. Use nonces or hashes instead.

The mistake

Not testing with Report-Only before enforcing.

The fix

Switching to enforcing without testing breaks scripts. Use Report-Only first, fix violations, then enforce.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors