Content Security Policy Tutorial: From Zero to Production
A complete guide to implementing Content Security Policy. Learn how CSP prevents XSS attacks, how to write effective policies, and how to deploy without breaking your site.
Content Security Policy (CSP) is the most powerful security header available to web developers. It controls which resources the browser is allowed to load, making it extremely difficult for attackers to execute injected scripts, load malicious styles, or exfiltrate data.
What CSP Protects Against
CSP is primarily designed to prevent Cross-Site Scripting (XSS) attacks. When an attacker finds a way to inject JavaScript into your page—through a comment field, URL parameter, or third-party widget—CSP can prevent that script from executing. CSP also prevents data exfiltration, clickjacking, and mixed content issues.
CSP Directives
The core directives you need to know:
- default-src: Fallback for most resource types
- script-src: Which scripts can execute
- style-src: Which stylesheets can load
- img-src: Which images can load
- connect-src: Which URLs can be fetched via JavaScript
- font-src: Which fonts can load
- frame-src: Which sites can embed this page
Building Your First Policy
Start with a Report-Only policy to identify violations without blocking anything: `Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report-endpoint`
Monitor the violation reports for a few weeks. Add legitimate third-party sources you use (Google Analytics, Stripe, YouTube, etc.). Once violations stabilize, switch to an enforcing policy.
Common Pitfalls
- Using `'unsafe-inline'` defeats the purpose of CSP - Forgetting to whitelist third-party services your site depends on - Not testing in all browsers (Safari has different CSP behavior than Chrome) - Setting CSP without a report-uri (you will not know when it breaks)
Testing Your CSP
Use our free Security Headers Checker to see your current CSP header. Start with Report-Only mode, monitor violations, fix issues, then enforce.