What is a Content Security Policy (CSP)?
Content Security Policy (CSP) is an HTTP response security header that restricts the resources (JavaScript, CSS, Images, Frames, WebSockets) a browser is allowed to load for a given web page. By declaring approved sources, CSP serves as the primary defense against Cross-Site Scripting (XSS), data injection, and clickjacking attacks.
Core CSP Directives Explained
default-src:Acts as the baseline fallback for all fetch directives if a specific directive (likescript-srcorconnect-src) is not declared.script-src:Governs where JavaScript files can be downloaded from and whether inline<script>tags are permitted. Avoid'unsafe-inline'and'unsafe-eval'in production.frame-ancestors:Modern replacement for the legacyX-Frame-Optionsheader, restricting which external domains are allowed to embed your page inside an<iframe>.upgrade-insecure-requests:Automatically rewrites all legacyhttp://URLs on the page to securehttps://before initiating network requests.
Testing with Report-Only Mode
When first rolling out a CSP in production, deploy with the Content-Security-Policy-Report-Only header. This logs policy violations to your reporting endpoint without breaking site functionality for legitimate users.