RMRM Full Stack & AI Engineer · All guides · Roadmaps
Security · guide

Content Security Policy (CSP)

Content Security Policy is an HTTP response header mechanism that allows web servers to declare which content sources browsers are permitted to load and execute, dramatically reducing the attack surface for cross-site scripting (XSS) and data injection attacks.

What Is CSP?

CSP is a security layer delivered via the Content-Security-Policy HTTP response header (or a <meta> tag) that instructs the browser on which origins, scripts, styles, images, and other resources are considered trustworthy. Any resource not matching the declared policy is blocked before it executes. It acts as a browser-enforced allowlist, not a server-side filter. This makes it a second line of defense rather than a replacement for input sanitization.

Why CSP Matters

XSS is consistently one of the top web vulnerabilities, allowing attackers to inject malicious scripts that steal cookies, hijack sessions, or exfiltrate data. A well-configured CSP prevents injected scripts from running even if sanitization fails. It also mitigates clickjacking, mixed-content issues, and unwanted third-party resource loading. Modern browsers have near-universal support, making CSP a low-cost, high-impact security control.

How CSP Works

When the browser receives a response with the Content-Security-Policy header, it parses the directives before rendering the page. Each directive controls a specific resource type: script-src governs JavaScript, style-src governs CSS, img-src governs images, connect-src governs fetch and XHR targets, and so on. If a resource's origin does not match the allowlist for its directive, the browser blocks it and optionally logs a violation report to a report-uri or report-to endpoint. The default-src directive acts as a fallback for any resource type not explicitly declared.

Key Directives Explained

script-src 'self' allows only same-origin scripts; adding 'nonce-<base64>' permits specific inline scripts by embedding a matching nonce attribute in the <script> tag. The 'unsafe-inline' and 'unsafe-eval' keywords disable much of CSP's protection and should be avoided. Using hashes (e.g., 'sha256-<hash>') is a safer alternative for allowing specific inline scripts without opening the door to all inline code. The upgrade-insecure-requests directive automatically upgrades HTTP sub-resource requests to HTTPS.

Report-Only Mode & Deployment

The Content-Security-Policy-Report-Only header enforces nothing but sends violation reports to your designated endpoint, making it safe to test a policy in production without breaking the site. Start with a restrictive policy in report-only mode, collect violations, refine the policy, then switch to enforcement mode. Tools like Google's CSP Evaluator or the report-uri.com service help analyze and harden policies. Iterative deployment is critical because an overly restrictive policy deployed all at once will block legitimate resources and break functionality.

Common Gotchas & Best Practices

Avoid 'unsafe-inline' in script-src; it negates protection against most XSS attacks and is often added as a quick fix when inline scripts break. CDN-hosted scripts should be allowed by specific origin rather than using the wildcard (*), which bypasses the policy entirely. CSP does not protect against server-side injection or SQL injection, so it must complement—not replace—robust input validation. Always pair CSP with other headers like X-Frame-Options (or frame-ancestors), Strict-Transport-Security, and X-Content-Type-Options for layered defense.

Go deeper with an AI tutor that teaches this in context — and quizzes you on it.
Open the app — free to start

© RM Full Stack & AI Engineer · All guides · Roadmaps · Open the app