Designing Hardened Content-Security-Policy Headers Without Breaking Production
Content-Security-Policy (CSP) is the browser's strongest defense-in-depth control against Cross-Site Scripting (XSS), data exfiltration, and clickjacking. Two subtle syntax traps break deployments constantly: keyword tokens like 'self', 'none', and 'strict-dynamic' MUST be wrapped in single quotes (otherwise browsers treat bare self as a hostname https://self/), and frame-ancestors is ignored inside <meta http-equiv> tags—it only works in real HTTP response headers.
Always roll out strict policies using Content-Security-Policy-Report-Only first with a reporting endpoint before switching to enforcement. Adding object-src 'none', base-uri 'self' (or 'none'), and frame-ancestors 'none' closes three classic bypasses that default-src 'self' alone does not cover.
- Fetch & Document Directivesdefault-src, script-src, style-src, img-src, font-src, connect-src, media-src, object-src, base-uri, form-action, frame-ancestors.
- Automated Security AuditFlags 'unsafe-inline'/'unsafe-eval' in script-src, missing object-src 'none', unquoted self/none typos, and wildcard * sources.
- Deploy SnippetsExports HTTP header, Content-Security-Policy-Report-Only, Nginx add_header, Apache Header set, and Vercel/Netlify _headers.
Why does frame-ancestors not work inside an HTML <meta> CSP tag?
Per the W3C CSP3 specification, frame-ancestors, report-uri, and sandbox are ignored in <meta http-equiv="Content-Security-Policy"> tags and must be sent as HTTP response headers.
Does default-src 'self' automatically protect base-uri and form-action?
No. Neither base-uri nor form-action nor frame-ancestors falls back to default-src—each must be declared explicitly.
Why is 'unsafe-inline' dangerous inside script-src?
Allowing 'unsafe-inline' in script-src lets injected <script> tags and onclick= attributes execute, neutralizing CSP's primary XSS protection. Use cryptographic nonces or SHA-256 script hashes instead.