The Practical Developer

Security Headers in Production: CSP, HSTS, and the Headers Your API Is Missing

A pentest found an XSS hole in your app. Your CDN is not setting HSTS. And your Content-Security-Policy either does not exist or lets everything through. Here is the header-by-header guide to fixing the six headers every production site and API should ship, with working middleware code and a CSP builder that does not make you hate yourself.

Server rack with blinking network lights, the infrastructure layer where missing security headers leave your applications exposed

The pentest report landed at 4:00 PM on a Friday. Thirty findings, but one line stopped the room: “Stored XSS in the user profile page. Cookie accessible via JavaScript. No CSP present.” The fix was simple on paper (sanitize the input, add some headers), but the headers part turned into a week-long project because nobody on the team knew what a realistic Content-Security-Policy looked like for an app that loads four different analytics scripts, two widget libraries, and embeds tweets.

This is the state of security headers in most production apps in 2026. They are either missing entirely, copy-pasted from a blog without understanding, or locked down so aggressively that the frontend team has to relax them weekly to unblock a new vendor script. There is a middle ground, and it starts with understanding the six headers that actually matter.

The six headers your application needs

Not every security header is worth your time. Feature-Policy is dead. X-XSS-Protection was deprecated when browsers removed XSS auditor support. And Expect-CT became irrelevant after Chrome 61. The headers below are the ones that still matter in 2026, backed by every major browser, and required by security standards like OWASP ASVS and the Mozilla Observatory.

1. Strict-Transport-Security (HSTS)

This header tells the browser to only connect to your domain over HTTPS, even if the user types http:// or clicks an old HTTP link. One request can prevent SSL-strip attacks for months.

Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

The parameters are not optional:

  • max-age=63072000 is two years. This is the minimum for HSTS preload.
  • includeSubDomains extends the policy to every subdomain, including api.yoursite.com and admin.yoursite.com.
  • preload is a flag to the browser that your domain can be hardcoded into the browser’s HSTS preload list. It is a one-way door. Once you are on the list, you cannot remove your domain from HTTPS enforcement for the duration set by the browser vendor (often years).

Do not ship preload on your first deploy. Serve max-age=300 for a week, then max-age=63072000 without preload for another week, then add preload only after you have confirmed every single subdomain serves HTTPS. The HSTS preload list does not care about your staging subdomain that still runs HTTP.

2. Content-Security-Policy (CSP)

This is the most powerful header and the one most teams get wrong. CSP lets you tell the browser exactly which sources of content are allowed to execute. A properly tuned CSP blocks inline scripts, stops XSS even if an attacker injects a <script> tag, and prevents data exfiltration by restricting where the page can make requests.

A reasonable starting policy for a content site with analytics:

Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com https://www.google-analytics.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://images.unsplash.com https://www.google-analytics.com; connect-src 'self' https://api.yourbackend.com; font-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'

That is ugly, and it will break things on your first deploy. That is normal. The key is to start with Content-Security-Policy-Report-Only and a report-uri before you enforce anything.

The CSP deployment workflow:

  1. Set Content-Security-Policy-Report-Only with report-uri https://your-report-endpoint.example.com/report.
  2. Watch the reports for a week. Every blocked resource is a legitimate script you forgot to allow.
  3. Triage each violation: add legitimate sources, fix insecure patterns, document deliberate exceptions.
  4. Only after the report-only policy has been clean for a week, switch to Content-Security-Policy enforcement.

The one CSP mistake that kills performance:

'unsafe-inline' on script-src defeats the entire purpose of CSP. It tells the browser “inline scripts are fine,” which is the exact vector CSP is meant to block. The alternative is to use a nonce or a hash. A nonce is a per-request random value:

Content-Security-Policy: script-src 'nonce-abc123' 'strict-dynamic'

Every <script> tag in your HTML gets nonce="abc123" (a fresh random value per request). 'strict-dynamic' allows scripts loaded by those trusted scripts to also execute, which handles the common case where your boot script dynamically loads a module. The nonce approach is harder to implement than 'unsafe-inline' because your templating engine or framework must inject the nonce into every script tag. But it is the only CSP configuration that actually prevents XSS.

3. X-Content-Type-Options

The simplest header you will set today:

X-Content-Type-Options: nosniff

This tells the browser not to MIME-sniff the response. Without it, an attacker can upload an HTML file disguised as image.jpg and the browser will render it as HTML, enabling XSS. nosniff forces the browser to respect the Content-Type header. If you serve Content-Type: image/jpeg, the browser must treat it as an image, not HTML.

There is no debate about this header. Every response from your origin should include it. Every CDN should forward it. There is no downside.

4. X-Frame-Options (or frame-ancestors in CSP)

X-Frame-Options: DENY

Prevents clickjacking by blocking your page from being embedded in an iframe on another domain. If you need to allow embedding on specific domains, use CSP’s frame-ancestors instead, which is more granular:

Content-Security-Policy: frame-ancestors 'self' https://trusted-partner.com

If you set both, frame-ancestors takes precedence in modern browsers and X-Frame-Options acts as a fallback for older ones. Set DENY unless you have a specific embedding use case.

5. Referrer-Policy

Controls how much referrer information is sent with requests leaving your site:

Referrer-Policy: strict-origin-when-cross-origin

This sends the full URL as referrer for same-origin requests, only the origin (no path or query string) for cross-origin requests over HTTPS, and nothing when navigating from HTTPS to HTTP. It is the safest default that does not break analytics referrer tracking.

6. Permissions-Policy (formerly Feature-Policy)

Replaces the deprecated Feature-Policy header. Controls which browser features your page can access:

Permissions-Policy: camera=(), microphone=(), geolocation=(), interest-cohort=()

The fourth value, interest-cohort=(), opts your site out of Google’s Topics API for ad targeting. Include it even if you do not care about ad privacy, because the default is opt-in and browsers may change the default over time.

One middleware to set them all

Here is a complete Express/Fastify-compatible middleware function that sets all six headers with safe defaults:

import { randomBytes } from 'node:crypto';
import type { Request, Response, NextFunction } from 'express';

interface SecurityHeadersOptions {
  cspDirectives?: Record<string, string[]>;
  hstsMaxAge?: number;
  hstsIncludeSubdomains?: boolean;
  isDev?: boolean;
}

export function securityHeaders(opts: SecurityHeadersOptions = {}) {
  const {
    cspDirectives = {},
    hstsMaxAge = 63072000,
    hstsIncludeSubdomains = true,
    isDev = process.env.NODE_ENV === 'development',
  } = opts;

  return function middleware(req: Request, res: Response, next: NextFunction) {
    // Generate per-request CSP nonce
    const nonce = randomBytes(16).toString('base64url');
    res.locals.cspNonce = nonce;

    // Build CSP from directives
    const directives: Record<string, string[]> = {
      'default-src': ["'self'"],
      'script-src': [`'nonce-${nonce}'`, "'strict-dynamic'"],
      'style-src': ["'self'", "'unsafe-inline'"],
      'img-src': ["'self'", 'data:', 'https://images.unsplash.com'],
      'connect-src': ["'self'"],
      'font-src': ["'self'"],
      'frame-ancestors': ["'none'"],
      'base-uri': ["'self'"],
      'form-action': ["'self'"],
      'report-uri': ['/__csp-report'],
      ...cspDirectives,
    };

    const cspValue = Object.entries(directives)
      .map(([key, values]) => `${key} ${values.join(' ')}`)
      .join('; ');

    // Set headers
    res.setHeader(
      'Content-Security-Policy',
      isDev
        ? `${cspValue}; Content-Security-Policy-Report-Only`
        : cspValue
    );

    res.setHeader(
      'Strict-Transport-Security',
      `max-age=${hstsMaxAge}${hstsIncludeSubdomains ? '; includeSubDomains' : ''}`
    );

    res.setHeader('X-Content-Type-Options', 'nosniff');
    res.setHeader('X-Frame-Options', 'DENY');
    res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
    res.setHeader(
      'Permissions-Policy',
      'camera=(), microphone=(), geolocation=(), interest-cohort=()'
    );

    next();
  };
}

The nonce generation is the critical piece. Every request gets a unique nonce, and your templates must apply it to every <script> tag. In a framework like Astro, you access it through middleware or a custom integration. In a plain Express app rendering HTML, you pass res.locals.cspNonce to your template engine.

Where to set these headers: origin, CDN, or both?

The answer depends on whether you control the origin and how your architecture is laid out.

If you use a CDN like Cloudflare, Fastly, or Akamai: set HSTS and X-Content-Type-Options at the CDN edge. These headers are static and apply to every response. Setting them at the edge means they are applied even if your origin is temporarily unreachable or serving a fallback page. CSP, on the other hand, should be set at the origin because it needs the per-request nonce.

If you do not use a CDN: set everything at the origin. The middleware above works as-is.

Hybrid approach: set the static headers (HSTS, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, X-Frame-Options) at the CDN, and set CSP at the origin. This lets your CDN handle the boilerplate while keeping CSP dynamic.

Testing your headers

Before you deploy, run these checks:

# Quick header check
curl -sI https://yoursite.com | grep -i -E '^(strict-transport-security|content-security-policy|x-content-type-options|x-frame-options|referrer-policy|permissions-policy)'

# Full header dump
curl -sI https://yoursite.com | head -20

# Check CSP with violations (requires a browser)
# Open DevTools > Console > look for CSP violation warnings

For a thorough audit, use these free tools:

Run these tools against your staging environment before production. Run them weekly in production. Set up a CI check that fails if the grade drops below A.

Common CSP mistakes and how to fix them

Mistake 1: 'unsafe-inline' instead of a nonce.

“This is fine because we control our scripts.” No, you do not. If an attacker injects a <script> tag, 'unsafe-inline' lets it execute. The nonce approach is the only CSP configuration that provides real XSS protection. The migration from 'unsafe-inline' to a nonce usually takes a day of template work and zero runtime cost.

Mistake 2: Using https: as a scheme source for scripts.

Content-Security-Policy: script-src https:

This allows any script served over HTTPS from any domain. That is not a security policy. It is a formality. Specify exact domains.

Mistake 3: Not setting a report-uri.

Without a report endpoint, you are flying blind. Violations are silently dropped. Use a service like report-uri.com, or build a simple endpoint that logs to your error tracker:

// CSP report endpoint (Express)
app.post('/__csp-report', express.json({ type: 'application/csp-report' }), (req, res) => {
  // Log to your observability system
  console.error('CSP Violation:', JSON.stringify(req.body, null, 2));
  res.status(204).end();
});

Mistake 4: Ignoring violation reports for more than a week.

Set up an alert. A new CSP violation pattern that appears after a deploy means something is broken. The frontend team should own the CSP report triage, because they are the ones who will know whether a blocked script is a new dependency or an actual attack.

The no-excuses baseline

If you take nothing else from this post, ship these five headers on every response today:

Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=(), interest-cohort=()

These five headers require zero application changes. They do not depend on your framework, your templating engine, or your frontend architecture. They can be set at the CDN edge or in a reverse proxy. They will improve your Mozilla Observatory score from F to B+ in one deploy. Add a reasonable CSP with a nonce and report-uri, and you hit A+.

Your application already trusts its own responses. These headers make sure the browser does too. The cost is a few kilobytes of configuration. The cost of not setting them is the next pentest report that starts with “Stored XSS.”

A note from Yojji

The gap between “I set some headers” and “these headers actually protect my users” is the same gap that separates a demo from a production deployment. Tuning a CSP nonce, setting up a report endpoint, and establishing a weekly triage process for violations is unglamorous operational work that most teams skip until an auditor forces the issue. Yojji’s engineering teams have built that discipline into Node.js backends and cloud-native deployments for clients across finance, healthcare, and e-commerce, where security headers are not optional and violations are monitored as closely as error rates.

Yojji is an international custom software development company founded in 2016, with offices in Europe, the US, and the UK. Their senior engineers specialize in the JavaScript ecosystem, cloud infrastructure on AWS/Azure/Google Cloud, and the full cycle of product delivery from discovery through production operations.