Web Fundamentals

Content Security Policy (CSP)

mediumWeb Fundamentals

Content Security Policy (CSP)

Learn the interview-ready mental model, practical trade-offs, and production patterns for this web fundamentals topic.

Topic content

TL;DRCSP restricts resource loading (scripts, styles, etc.) to approved sources. Use it to block XSS by preventing unauthorized script execution.
High Signal
Google
Meta
Netflix
Agoda
30-Second Answerstart every interview with this

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.

Page loads with CSP header
Browser sees external resource request
Check against CSP policy
Allowed → Load | Blocked → Error in console

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.

Key Takeaways
  • 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.)