What Is a CSP in Web Security? A Practical Guide

Content Security Policy (CSP) is an HTTP response header that tells the browser which resources a page may load. It’s a primary defense against cross-site scripting (XSS), clickjacking, and data injection. Instead of trusting every script that appears on the page, you declare an allowlist — and the browser blocks everything else.

A CSP is sent as a header such as Content-Security-Policy: default-src 'self'. Any resource not permitted by the policy simply won’t load or execute, which stops injected scripts from stealing cookies or tokens.

Article illustration

How CSP Works

Each directive controls one resource type: scripts, styles, images, fonts, frames, or network connections. The browser checks every request against the policy before making it.

Key Directives

  • default-src — fallback for all resource types
  • script-src — the most important; controls JavaScript
  • style-src — limits CSS sources
  • connect-src — restricts fetch, XHR, and WebSockets
  • frame-ancestors — replaces X-Frame-Options

Rolling Out CSP Safely

Start with Content-Security-Policy-Report-Only, which logs violations without blocking anything. Fix what breaks, then switch to enforcing mode. Avoid ‘unsafe-inline’ and ‘unsafe-eval’ — they weaken the policy dramatically. Use nonces or hashes for inline scripts, and add a report-uri endpoint to monitor attacks in production.

Conclusion

CSP won’t fix vulnerable code, but it’s a powerful second layer of defense. Deploy it in report-only mode, tighten it gradually, and you’ll neutralize most XSS attempts before they ever run.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *