You can ship strong, measurable protection against common web attacks in a single afternoon. The trick isn’t syntax—it’s rolling out a Content Security Policy (CSP) and a handful of browser headers without breaking your app, analytics, payments, or customer-embedded workflows. This guide walks through the why, what, and how, with pragmatic examples for single-page apps, multi-tenant SaaS, file uploads, and third-party integrations.
What these headers actually protect
Security headers reduce entire classes of risk by telling browsers how to load, isolate, and share resources. A concise mapping:
- Cross-site scripting (XSS): Controlled by CSP (
script-src, nonces/hashes, nounsafe-inline),X-Content-Type-Options(no MIME sniffing), and careful cookie flags. - Clickjacking: Controlled by CSP
frame-ancestors(or legacyX-Frame-Options), preventing hostile sites from framing your app. - Data exfiltration and mixed content: CSP
connect-src/img-src/media-srcand HSTS to enforce HTTPS. - Cross-origin confusion: Cross-origin isolation headers (
COOP/COEP/CORP) when you need strong isolation or advanced APIs. - Over-permissive capabilities:
Permissions-Policyto disable features you don’t use (camera, mic, geolocation, etc.). - Leaky referrers:
Referrer-Policyto avoid sending sensitive path/query data to other origins.
Principles before you touch a header
- Start strict in Report-Only: Ship CSP in
Content-Security-Policy-Report-Onlyfirst. Collect violations, tune, then enforce. - Prefer nonces or hashes over wildcards:
'unsafe-inline'and*punch holes attackers love. Use nonces on scripts and styles your app injects. - Inventory your resources: Scripts, images, fonts, workers, WebSockets, analytics, error reporting, payments; list domains and protocols.
- Headers over meta tags: Use HTTP headers so your CDN and middlewares apply them consistently and early.
- Measure, then tighten: Keep a feedback loop: reports → dashboards → safe auto-tuning (never auto-whitelist blindly).
The essential header set
Content-Security-Policy (CSP)
CSP constrains what your app can load and execute. A practical, safe baseline favors explicit allowlists:
Content-Security-Policy: default-src 'none base-uri 'self script-src 'self' 'nonce-' 'strict-dynamic style-src 'self' 'nonce- img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' https://api.example.com wss://realtime.example.com; frame-src 'self frame-ancestors 'self object-src 'none worker-src 'self' blob:; manifest-src 'self form-action 'self upgrade-insecure-requests; report-to csp-endpoint; report-uri https://reports.example.com/csp
Notes:
default-src 'none': Forces you to explicitly allow each type of resource.- Nonces: Generate a fresh, high-entropy nonce per response and attach it to every script/style tag you control. Avoid
'unsafe-inline'and'unsafe-eval'. 'strict-dynamic': Allows nonce-bearing scripts to load other scripts without whitelisting each origin. Useful for modern bundlers and module loaders.- Data/blob allowances: Many apps use
data:for small inline images orblob:for downloads/workers. Only add when needed. - WebSockets: Use
wss:inconnect-srcfor real-time features. frame-ancestorsbeatsX-Frame-Options: Prefer CSP for framing control. It’s more flexible and standard.- Reporting:
report-tois the newer reporting mechanism; keepreport-urifor older browsers.
Ship CSP in Report-Only first
Content-Security-Policy-Report-Only: default-src 'none script-src 'self' 'nonce-' 'strict-dynamic ...; report-to csp-endpoint; report-uri https://reports.example.com/csp
Let it run for days across staging and a small percentage of production traffic. Triage violations, remove dead integrations, and tighten your allowlist before enforcing.
Strict-Transport-Security (HSTS)
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
- Enforces HTTPS and tells browsers to never downgrade to HTTP.
- Caution with
includeSubDomains: Only enable if every subdomain (present and future) will serve HTTPS correctly. In multi-tenant systems with customer subdomains, ensure your wildcard routing and certificates are comprehensive before enabling.
Referrer-Policy
Referrer-Policy: no-referrer-when-downgrade
Reasonable defaults include strict-origin-when-cross-origin (good balance) or no-referrer (most privacy). Choose based on your analytics/attribution needs.
Permissions-Policy
Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), usb=(), fullscreen=(self)
Disable capabilities you don’t use. Add exceptions per feature and surface as feature flags where applicable.
X-Content-Type-Options
X-Content-Type-Options: nosniff
Prevents browsers from MIME-sniffing script and style resources, which can bypass type checks.
COOP, COEP, CORP (Cross-origin isolation)
Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp Cross-Origin-Resource-Policy: same-site
Use if you need advanced APIs (e.g., high-res timers, SharedArrayBuffer) or tighter cross-origin isolation. These require your dependencies (scripts, images, workers) to advertise appropriate CORP/CORS headers. Roll out carefully.
Legacy/obsolete headers
- X-Frame-Options: Use CSP
frame-ancestorsinstead unless you need legacy support. - X-XSS-Protection: Deprecated. Do not rely on it.
- Expect-CT: Largely obsolete with modern certificate tooling.
How to roll out CSP without breaking prod
- Inventory resources: List your script, style, image, font, worker, and network endpoints. Include analytics, error tracking, customer chat, payments, and storage endpoints.
- Start minimal in Report-Only:
default-src 'none'. Addscript-src/style-srcwith nonces and'self'. Add the bare minimum forconnect-src,img-src,font-src, etc. - Turn on reporting: Send violation reports to a dedicated endpoint you control. Normalize and dedupe (user agents can be noisy).
- Exercise critical workflows: Login, onboarding, billing, exports, real-time updates, embedded widgets. Run automated tests and explore edge cases manually.
- Iterate surgically: When you add an origin, prefer exact hosts over wildcards. Revisit after a week; tighten if you see dead or rare origins.
- Enforce in phases: Start with internal/staging, then a small production cohort, then all users. Keep Report-Only alongside Enforce for a release or two to catch regressions.
Nonces, hashes, and modern bundlers
Inline scripts and styles are the most common source of CSP pain.
- Prefer nonces: Generate a random nonce per response and attach to your controlled