Content Security Policy: The Header That Stops XSS Dead
Content Security Policy is one of the most effective XSS defenses available. Most sites don't have one. Here's how to add it without breaking your site.
XSS (Cross-Site Scripting) is consistently in OWASP's top 10 web vulnerabilities. The main defense is escaping user input. But bugs happen. A Content Security Policy is the defense in depth that limits damage when a bug slips through.
Starting With Report-Only
Never deploy CSP directly to enforcement on an existing site. Use report-only first:
Add a simple route to log violation reports. Run this for two weeks in production. Collect what would have been blocked. You'll see analytics scripts, fonts from Google, CDN resources, chat widgets — everything that needs to be explicitly allowed.
Building Your Actual Policy
Based on your violation report, add legitimate sources:
The Inline Script Problem
'unsafe-inline' for scripts defeats most of CSP's protection. Any XSS injection is also inline. If you need it, use nonces instead — random values that allow only your legitimate inline scripts.
For Next.js, the recommended approach is automatic nonce generation in middleware. Each page gets a fresh nonce, inline scripts are tagged with it, and the CSP header is set with that nonce. Injected scripts can't have a nonce they don't know in advance.
Quick Wins Before Full CSP
Even a loose CSP is better than none. Start with these headers, which are simpler to add and provide real protection:
- X-Frame-Options: DENY — prevents clickjacking
- X-Content-Type-Options: nosniff — prevents MIME type sniffing
- Referrer-Policy: strict-origin-when-cross-origin — limits referrer data leakage
- Permissions-Policy: camera=(), microphone=() — restricts powerful browser APIs
Frequently Asked Questions
What is Content Security Policy?+
Why don't more sites implement CSP?+
What is the difference between CSP report-only mode and enforcement mode?+
What is a nonce in CSP?+
🔧 Free Tools Used in This Guide
FreeToolKit Team
FreeToolKit Team
We build free browser-based tools and write practical guides that skip the fluff.
Tags: