Content Security Policy (CSP)

Why CSP Exists

The Same-Origin Policy keeps documents isolated, but it doesn’t control which scripts can run on a page. CSP fills that gap: the server sends a Content-Security-Policy header and the browser enforces a whitelist of trusted sources for scripts, styles, fonts, images, frames, and more. Anything not on the list simply never executes.

Core Directives

DirectiveWhat it locks down
script-srcAllowed origins for JavaScript files or inline scripts (hashes/nonces required if inline).
style-srcAllowed locations for CSS.
img-srcWhere images may load from.
default-srcFallback policy if a more specific directive isn’t provided.

Directives can reference keywords such as 'self' (current origin), 'none', hashes, or nonces generated per response. A typical header might look like:

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; object-src 'none';

Inline vs Remote Scripts

Inline scripts

If 'unsafe-inline' is omitted (or you explicitly set script-src 'self'), the browser refuses to run <script>...</script> blocks unless they’re protected by a nonce or hash. This blocks the most common XSS payloads injected via HTML templates.

Remote scripts

Only the hosts listed in script-src are trusted. A third-party <script src="https://unlisted.cdn.com/app.js"> simply never loads because it’s not on the whitelist. This is how CSP stops unauthorized widgets, miners, or surprise dependencies even if they’re added to the DOM.