What is Content Security Policy (CSP)?

Answer

Content Security Policy (CSP) is an HTTP response header that tells browsers which sources of content (scripts, styles, images, fonts, etc.) are trusted and allowed to load. It is the most effective defense against XSS. Example header: Content-Security-Policy: default-src 'self'; script-src 'self' cdn.example.com; style-src 'self' 'unsafe-inline'. Directives: default-src (fallback for all types), script-src (JavaScript sources), style-src, img-src, connect-src (fetch/XHR), frame-ancestors (prevents clickjacking). 'self' means only the same origin. 'none' blocks everything. Avoid 'unsafe-inline' (allows inline scripts — the main XSS vector) and 'unsafe-eval'. Use nonce or hash for legitimate inline scripts. Report-only mode (Content-Security-Policy-Report-Only) tests policies without enforcing them.