Overview
This page is the atomic definition. Security header configuration for specific frameworks lives at nextjs and astro.
Definition
Content Security Policy (CSP) is a browser security mechanism delivered via the Content-Security-Policy HTTP response header (or a <meta> tag, though the header is preferred). It declares an allowlist of trusted origins for each resource type: scripts (script-src), styles (style-src), images (img-src), fonts (font-src), API connections (connect-src), frames (frame-ancestors), and more. When a browser encounters a resource from an unlisted origin, it blocks the request and optionally reports the violation to a report-uri endpoint. The goal is defense-in-depth against Cross-Site Scripting (XSS): even if an attacker injects a <script> tag, the browser refuses to execute it if the source is not in the policy. script-src 'self' allows only same-origin scripts. script-src 'nonce-abc123' allows only scripts carrying that nonce, which the server injects per request. unsafe-inline disables this protection for inline scripts and should be avoided. CSP operates independently of cors, which controls cross-origin data access rather than resource loading.
When it applies
Apply CSP to every page that serves dynamic content or accepts user input. Start with Content-Security-Policy-Report-Only to log violations without breaking anything, then tighten to enforcement mode. Strict CSP is essential for financial, healthcare, and authentication-facing pages.
Example
A Next.js app sets:
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-abc123'; style-src 'self' 'unsafe-inline'; img-src 'self' data:
This allows only same-origin scripts (plus the nonce-tagged inline script Next.js injects), same-origin plus inline styles, and data-URI images.
Related concepts
- cors - controls which origins can read API responses; complements CSP.
- http-codes - CSP violations are logged in browser DevTools, not via HTTP status codes.
- nextjs - Next.js provides a
headers()config key for setting CSP. - technical - overly strict CSP can block analytics and SEO scripts if not whitelisted.
Citing this term
See CSP (llmbestpractices.com/glossary/csp).