Content-Security-Policy (CSP) Header Explained
Content-Security-Policy (CSP) is an HTTP response header that tells browsers which sources of content are allowed to load on your page. It is the single most effective defense against Cross-Site Scripting (XSS) attacks because it prevents the browser from executing inline scripts or loading resources from unauthorized origins.
Recommended Value
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'
What Each Directive Does
| Directive | Purpose |
|---|---|
default-src 'self' | Only allow resources from the same origin by default |
script-src 'self' | Only allow JavaScript from the same origin — blocks inline scripts |
frame-ancestors 'none' | Prevents your page from being embedded in iframes (clickjacking defense) |
base-uri 'self' | Prevents attackers from changing the base URL for relative URLs |
form-action 'self' | Restricts where forms can submit data to |
What Happens Without This Header
Without CSP, attackers can inject arbitrary scripts via XSS vulnerabilities, steal session cookies, redirect users to phishing pages, or mine cryptocurrency in the background. CSP does not prevent the vulnerability itself, but it prevents the browser from executing the injected payload.
How to Implement
# Nginx
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none';" always;
# Apache
Header always set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none';"
# Express.js
app.use((req, res, next) => {
res.setHeader('Content-Security-Policy',
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none';"
);
next();
});
Testing and Report-Only
Use Content-Security-Policy-Report-Only first to test your policy without breaking anything. This header logs violations to a reporting endpoint without blocking content. Once you've resolved all violations, switch to the enforcing header.
Related Questions
Scan your system prompt with LochBot — free, client-side, no data sent anywhere.