Content Security Policy (CSP)
Learn the interview-ready mental model, practical trade-offs, and production patterns for this web fundamentals topic.
Topic content
Content Security Policy (CSP) is an HTTP security header that tells the browser which sources are allowed to load resources. It is one of the strongest defenses against XSS attacks by blocking inline scripts, unauthorized domains, and dangerous behaviors like eval().
The browser is a nightclub. CSP is the bouncer with a strict guest list. Only approved sources (domains, nonces, etc.) are allowed in. Any script or resource not on the list is blocked at the door.
1Core CSP Directives
default-src acts as fallback. script-src controls JavaScript sources. style-src controls CSS. object-src, img-src, etc. control other resource types.
2Nonces and Hashes for Inline Content
To safely allow inline scripts/styles, use nonces or hashes instead of 'unsafe-inline'. Nonces are generated per request and included in both the CSP header and script tags.
3Report-Only Mode
Use Content-Security-Policy-Report-Only to test your policy without blocking requests. Violations are reported but execution continues.
- ✓CSP is a powerful XSS defense by controlling resource sources
- ✓Start strict and relax specific directives as needed
- ✓Prefer nonces/hashes over 'unsafe-inline'
- ✓Use report-only mode to test policies safely
- ✓Combine with input sanitization and output encoding
- ✓Monitor CSP violation reports in production
- ✓CSP complements other security headers (HSTS, etc.)