Content Security Policy (CSP) Guide
A Content Security Policy (CSP) is a crucial HTTP response header that allows site administrators to declare approved sources of content that the browser may load. It is one of the most effective ways to mitigate Cross-Site Scripting (XSS) and data injection attacks.
Key Directives
default-src: Serves as a fallback for the other CSP fetch directives. If a specific directive (like font-src) is not defined, the browser will use default-src.script-src: Specifies valid sources for JavaScript. Never use 'unsafe-inline' unless absolutely necessary, as it negates much of the XSS protection CSP provides. Use nonces or hashes instead.style-src: Specifies valid sources for stylesheets.connect-src: Restricts the URLs which can be loaded using script interfaces (e.g., fetch, XHR, WebSockets).Testing Your CSP
Always use Report-Only Mode (Content-Security-Policy-Report-Only) when rolling out a new CSP to a production application. This allows you to monitor violations via the report-uri directive without breaking your site for real users. Once the policy is stable, switch to enforcing mode.