securitycspheaders

Implementing Content Security Policy with CSP Builder

A Content Security Policy header is one of the most effective defenses against XSS — and a CSP builder makes writing one far less error-prone.

5 min read

Related Tool

CSP Builder

Open tool

What CSP Prevents

Cross-site scripting (XSS) attacks inject malicious scripts into your page. A Content Security Policy tells the browser exactly which sources are allowed to load scripts, styles, images, and other resources. Even if an attacker injects a script tag, the browser refuses to execute it if the source is not on the allowlist.

Key Directives Explained

  • default-src: The fallback for resource types not covered by a more specific directive.
  • script-src: Controls JavaScript sources. This is the most important directive for XSS protection.
  • style-src: Controls CSS sources.
  • img-src: Controls image sources, including data URIs.
  • connect-src: Controls which URLs can be reached via fetch, XHR, and WebSocket.
  • frame-ancestors: Replaces the X-Frame-Options header for clickjacking protection.

Common Gotchas

unsafe-inline in script-src defeats most of the XSS protection. If you need inline scripts, use nonces or hashes instead. unsafe-eval should be avoided unless your framework requires it.

Report-Only Mode

Before enforcing a CSP, deploy it in report-only mode using the Content-Security-Policy-Report-Only header with a report-uri. Violations are logged but not blocked. This lets you audit what your page actually loads and fix gaps before enforcement breaks anything in production.

Using a CSP Builder

Hand-writing CSP strings is tedious and error-prone. A CSP builder lets you toggle directives and sources visually, then copies the complete header value ready to paste into your server config or middleware.