How to Implement Security Headers Beyond CSP
Add the security headers around CSP: HSTS, nosniff, Referrer-Policy, Permissions-Policy, and framing controls, and test they reach every response.
On this page
Introduction
Content-Security-Policy gets attention because it blocks script injection, but a set of smaller headers closes other browser-level gaps: forcing HTTPS, stopping type sniffing, controlling referrer leakage, and limiting powerful features a page does not need. Individually each is modest; together they remove a class of client-side weaknesses that CSP alone does not cover.
This tutorial covers the headers around CSP — HSTS, nosniff, Referrer-Policy, Permissions-Policy, and frame protection — what each does, how to apply them on every response, and how to test and monitor them. The examples use HTTP headers, which any stack can set.
Force HTTPS with HSTS
Strict-Transport-Security tells the browser to use HTTPS for this host for a period and to refuse to connect over HTTP, which protects against downgrade and cookie-stealing over plaintext. Once a browser has seen it, it will not allow a plain HTTP request to the host for the max-age, so the first visit after enabling should be over HTTPS and a subsequent plaintext attempt is blocked.
Because HSTS is remembered, it is dangerous to enable carelessly. Start with a short max-age, verify that every subdomain serves HTTPS, then raise it toward a year. Add includeSubDomains only when every subdomain is ready, because including a subdomain that does not serve HTTPS makes it unreachable over the network. Reserve preload for when you are certain, since preload lists are hard to leave.
function securityHeaders(res, opts) {
// HSTS: only meaningful over HTTPS, raise max-age after verification
res.setHeader('Strict-Transport-Security', 'max-age=' + opts.hstsMaxAge);
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader('Permissions-Policy', 'geolocation=(), camera=(), microphone=()');
}
Control type sniffing and referrers
X-Content-Type-Options: nosniff stops the browser from guessing a response’s type from its bytes. Without it, a response the server labels text/plain but that contains HTML can be sniffed and executed, turning a benign file upload or a user-controlled response into script execution. Send nosniff on every response; it has no legitimate downside for a server that sets correct content types.
Referrer-Policy limits how much of the current URL a browser sends when navigating or loading subresources from another origin. The default can leak paths, query strings, or tokens in the URL to third parties. strict-origin-when-cross-origin sends the full URL for same-origin requests and only the origin for cross-origin ones, which is a good default that preserves internal analytics without leaking paths externally.
// a strict referrer policy that still lets you see your own paths internally
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
Limit powerful features with Permissions-Policy
Permissions-Policy controls whether the page and its embedded frames may use powerful browser features: camera, microphone, geolocation, and others. Denying the ones you do not use reduces the impact of an injected script, which cannot call a feature the policy forbids, and it limits what a third-party iframe can access. Set a default-deny policy and enable only what a specific page needs.
Scope the policy to the frames that need a feature, using the origin syntax, rather than enabling it site-wide. A page that shows a map needs geolocation only inside the map frame, and everything else should be denied. This keeps the powerful features available precisely where they are used and nowhere else, which is the same least-privilege principle applied to browser capabilities.
Frame protection and other headers
Include the framing controls alongside CSP: frame-ancestors in the policy and X-Frame-Options as a legacy fallback, as covered elsewhere, so pages cannot be framed to hijack clicks. Add Cross-Origin-Resource-Policy and the cross-origin opener and embedder policies where you serve cross-origin content, to control which origins can load your resources and script. These enforce boundaries that CSP does not.
Keep the set coherent. A header that conflicts with another, such as a referrer policy that contradicts a CORS configuration, produces confusing behavior. List the headers you send, what each protects, and the intended value, and apply them from one place so the whole set is visible and reviewable rather than scattered across handlers.
function crossOriginHardening(res) {
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
}
Apply on every response and test
Set the headers at the outermost layer so every response carries them: HTML, JSON, errors, redirects, and downloads. A route that bypasses the layer, such as a health check or a static file handler, is the gap an attacker finds. Put the whole set in one middleware and assert in a test that a representative response from every route group has each header.
Crawl the routes and assert the headers are present and hold the intended values. Include the error and redirect paths, because those often skip the middleware. Monitor for regressions: a template change or a new handler that bypasses the middleware removes the headers silently, and a periodic scan catches it before an attacker does.
for P in / /login /api/data /does-not-exist; do
echo "== $P =="
curl -sD - -o /dev/null "http://localhost:3000$P" | grep -i -E 'strict-transport-security|x-content-type-options|referrer-policy|permissions-policy'
done
# every route group, including the 404, must carry the full set
Common pitfalls
Enabling HSTS with a long max-age or includeSubDomains before all subdomains serve HTTPS, omitting nosniff so a file can be sniffed as script, leaving the default referrer policy that leaks paths, a permissive Permissions-Policy, and setting the headers only on some routes are the recurring mistakes. A staged HSTS rollout, nosniff everywhere, a strict referrer policy, a default-deny feature policy, and a single global application address them.
Conclusion
The headers around CSP close gaps CSP leaves open. Staged HSTS forces HTTPS, nosniff stops type sniffing, a strict Referrer-Policy limits leakage, Permissions-Policy denies unused browser features, and the framing and cross-origin headers enforce boundaries. Apply the whole set from one place on every response. Self-check by crawling every route group and asserting each header is present with the intended value. Together they make the browser enforce the policy, not just the server.
Sources: OWASP: Secure headers project, MDN: Strict-Transport-Security, MDN: Permissions-Policy.
FAQ
- What does X-Content-Type-Options: nosniff do?
- It stops the browser from guessing a response's type from its content. Without it, a file the server sends as text/plain can be sniffed as HTML or script and executed. Sending nosniff everywhere is a cheap, high-value default.
- Is HSTS risky?
- It is powerful and hard to undo, because browsers remember it for the max-age. Ensure every subdomain serves HTTPS before including them, and start with a short max-age, verify, then raise it. A misconfigured HSTS can make an HTTP-only subdomain unreachable.
Report a problem with this articleOpens a pre-filled issue on GitHub.