CSP

What is a Content Security Policy? CSP Explained

XSS attacks work by injecting scripts into your page. CSP is a browser-enforced allowlist that controls which scripts, styles, and resources are allowed to run — blocking injected scripts even if they get into your HTML.

The problem CSP solves

Without CSP, if an attacker finds a way to inject <script src="https://evil.com/steal.js"></script> into your page, the browser runs it. With CSP, the browser checks if evil.com is in your allowlist — it is not, so the script is blocked.

How CSP works

Your server sends a Content-Security-Policy header with directives that define what is allowed. The browser enforces them when loading the page.

Content-Security-Policy:
  default-src 'self';
  script-src 'self' https://trusted-cdn.com;
  style-src 'self' https://fonts.googleapis.com;
  img-src 'self' data: https:;
  frame-ancestors 'none';
  object-src 'none';

The main directives

DirectiveControls
default-srcFallback for all resource types not explicitly listed
script-srcJavaScript files and inline scripts
style-srcCSS files and inline styles
img-srcImages
connect-srcXHR, fetch, WebSocket connections
font-srcFont files
frame-srcIframes your page loads
frame-ancestorsWho can embed your page in an iframe
object-srcPlugins (Flash etc) — set to none

Why unsafe-inline defeats CSP

Adding 'unsafe-inline' to script-src allows any inline script to run — including injected ones. It fixes the "inline script blocked" error but removes all XSS protection. Use nonces instead.

Start with report-only mode

Use Content-Security-Policy-Report-Only to test your policy without blocking anything. Violations appear in the browser console, letting you build your allowlist before enforcing.

Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self';
Generate a CSP for your page → CSPFixer