Why CSP Matters for Web Security
Content Security Policy is one of the most effective defenses against cross-site scripting (XSS) attacks. By declaring exactly which sources can load scripts, styles, images, and other resources, you create a whitelist that browsers enforce automatically. Even if an attacker injects malicious code into your page, the browser refuses to execute it because the source is not in your policy.
Understanding CSP Directives
Each directive controls a specific resource type. The default-src directive acts as a fallback for any unspecified type. The script-src directive governs JavaScript sources, style-src handles CSS, and img-src controls images. More specialized directives like connect-src restrict fetch and XMLHttpRequest targets, while frame-ancestors determines which sites can embed yours in an iframe.
Common Source Values Explained
The value 'self' allows content from your own origin. The value 'none' blocks everything for that directive. For inline scripts, 'unsafe-inline' permits them but weakens security; prefer nonce-based or hash-based approaches. The 'strict-dynamic' value trusts scripts loaded by already-trusted scripts, simplifying CDN usage while maintaining protection against injected code.
Deploying CSP in Production
Start with Content-Security-Policy-Report-Only to collect violation reports without breaking functionality. Analyze the reports, adjust your policy, and then switch to the enforcing header. Use report-uri or report-to directives to send violations to a logging endpoint. Monitor regularly because new third-party integrations or code changes may trigger unexpected blocks.





