Recipe

Content Security Policy

Lock down your browser runtime with a strict CSP that blocks inline scripts, eval, and untrusted origins — the single highest-leverage defense against XSS.

Why CSP first

XSS accounts for over 30% of all web vulnerabilities. A well-tuned CSP eliminates entire classes of attack by restricting what the browser is allowed to execute, load, and connect to. When combined with Trusted Types and Subresource Integrity, CSP forms the backbone of a defense-in-depth strategy for any production application.

The strict baseline

Content-Security-Policy:
  default-src 'none';
  script-src 'self';
  style-src 'self';
  img-src 'self' data:;
  font-src 'self';
  connect-src 'self';
  frame-ancestors 'none';
  base-uri 'self';
  form-action 'self';

This policy assumes no inline scripts or styles. All assets must be served from the same origin. Adjust connect-src and img-src for CDNs or third-party APIs.

Nonce-based approach

When inline scripts are unavoidable, use per-request cryptographic nonces. Generate a fresh 128-bit base64 nonce on every response and inject it into both the header and the script tag. Never reuse nonces across requests.

Content-Security-Policy:
  script-src 'nonce-rAnd0m' 'strict-dynamic';
  style-src 'nonce-rAnd0m';

Reporting

Deploy in report-only mode first. Collect violations for at least one full release cycle before enforcing. Use report-uri or the newer report-to directive with a Reporting API endpoint.

Content-Security-Policy-Report-Only:
  default-src 'self'; report-uri /csp-violations