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.
Advertisement
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?+
Advertisement
๐ง Free Tools Used in This Guide
Elena Kovac
Security & Privacy Analyst ยท 8+ years experience
Elena spent eight years as an application security analyst, auditing document-handling pipelines and password hygiene at mid-market firms. She covers PDFs, password generation, file-processing privacy, and the trade-offs between convenience and safety online.
View all posts by Elena Kovac โTags: