Concept Explanation
Your server does not only send HTML. It sends instructions about how the browser should treat that HTML. Security headers are those instructions, and they are the cheapest defense you will ever deploy: no refactor, no new dependency, just a few lines of config.
Think of your page as a nightclub. CSP is the guest list saying which scripts are allowed in. HSTS is the rule that nobody enters through the unlocked back door. X-Frame-Options stops a rival club from putting your dance floor behind their own glass wall.
The star is Content-Security-Policy. XSS defense normally means escaping every output correctly, forever, across every developer who ever touches the codebase. CSP is the safety net for the day someone slips: even if an attacker injects a <script>, the browser refuses to run it because it is not on the list.
Syntax or Core Structure
A reasonable starting policy
Content-Security-Policy:
default-src 'self';
script-src 'self' https://cdn.trusted.com;
style-src 'self';
img-src 'self' data: https:;
connect-src 'self' https://api.myapp.com;
frame-ancestors 'none';
base-uri 'self';
object-src 'none'
Setting them in Express
const helmet = require('helmet');
app.use(helmet()); // sensible defaults for a dozen headers
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", 'https://cdn.trusted.com'],
objectSrc: ["'none'"],
frameAncestors: ["'none'"]
}
}));
Key Features
| Header | What it does |
|---|---|
Content-Security-Policy | Restricts where scripts, styles, images and connections may come from |
Strict-Transport-Security | Forces HTTPS for a set duration, killing downgrade attacks |
X-Content-Type-Options: nosniff | Stops the browser guessing that your .txt is really a script |
X-Frame-Options / frame-ancestors | Prevents clickjacking by banning embedding |
Referrer-Policy | Limits how much URL detail leaks to third parties |
Permissions-Policy | Turns off camera, mic, geolocation for code you did not write |
Real World Example
Rolling out CSP without breaking production. Nobody gets the policy right on the first try, so the standard playbook is:
- Ship
Content-Security-Policy-Report-Onlywith areport-uri. The browser reports violations but blocks nothing. - Watch the reports for a week. You will discover an analytics snippet, an old inline
onclick, and a font CDN you forgot about. - Fix or allowlist each one, then flip the header to enforcing mode.
GitHub, Dropbox and Shopify all published write-ups of exactly this migration. It is a normal amount of work, not a sign you did something wrong.
Common Mistakes
script-src 'unsafe-inline'. This is the single line that undoes CSP, because injected inline scripts are precisely what you were defending against. Use a per-request nonce or a hash instead.'unsafe-eval'left in for one legacy library. It re-opens a wide door for a small convenience.- Setting HSTS with a long
max-agebefore HTTPS is solid everywhere. Browsers will remember and refuse plain HTTP, including on subdomains if you addincludeSubDomains. It is hard to walk back. - Assuming a meta tag is equivalent.
<meta http-equiv>CSP works but cannot expressframe-ancestorsorreport-uri. Prefer the real header. - Skipping
object-src 'none'andbase-uri 'self'. Both close well-known bypasses thatdefault-srcalone does not cover.
Best Practices
- Start in report-only mode. Always.
- Prefer nonces over allowlisting whole CDNs; a compromised CDN otherwise inherits your trust.
- Add
nosniff,Referrer-Policy: strict-origin-when-cross-originandframe-ancestors 'none'on day one. They almost never break anything. - Test headers in CI so a well-meaning refactor cannot silently drop them.
Practice Exercises
- The Header Reader: Open the Network tab on three large sites and copy their CSP. Identify one directive each that you had not seen before.
- The Report-Only Run: Add a strict
Content-Security-Policy-Report-Onlyheader to a small project and list every violation your own code produces. - The Clickjack Demo: Put your site in an
<iframe>on another page, confirm it loads, then addframe-ancestors 'none'and watch it refuse.