Security Headers: The Server's Instructions

Security Headers: The Server's Instructions in JavaScript: Your server does not only send HTML.

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

HeaderWhat it does
Content-Security-PolicyRestricts where scripts, styles, images and connections may come from
Strict-Transport-SecurityForces HTTPS for a set duration, killing downgrade attacks
X-Content-Type-Options: nosniffStops the browser guessing that your .txt is really a script
X-Frame-Options / frame-ancestorsPrevents clickjacking by banning embedding
Referrer-PolicyLimits how much URL detail leaks to third parties
Permissions-PolicyTurns 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:

  1. Ship Content-Security-Policy-Report-Only with a report-uri. The browser reports violations but blocks nothing.
  2. Watch the reports for a week. You will discover an analytics snippet, an old inline onclick, and a font CDN you forgot about.
  3. 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-age before HTTPS is solid everywhere. Browsers will remember and refuse plain HTTP, including on subdomains if you add includeSubDomains. It is hard to walk back.
  • Assuming a meta tag is equivalent. <meta http-equiv> CSP works but cannot express frame-ancestors or report-uri. Prefer the real header.
  • Skipping object-src 'none' and base-uri 'self'. Both close well-known bypasses that default-src alone 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-origin and frame-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

  1. 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.
  2. The Report-Only Run: Add a strict Content-Security-Policy-Report-Only header to a small project and list every violation your own code produces.
  3. The Clickjack Demo: Put your site in an <iframe> on another page, confirm it loads, then add frame-ancestors 'none' and watch it refuse.