patternjavascriptMajor
HSTS Header to Enforce HTTPS
Viewed 0 times
hstsstrict transport securityhttps enforcementssl strippingpreloadmax-age
Problem
Without HSTS, users who initially visit via HTTP can be intercepted (SSL stripping) before the server redirects them to HTTPS, exposing credentials and session tokens.
Solution
Set Strict-Transport-Security with a long max-age (at least one year), and include subdomains. Submit to the HSTS preload list for maximum protection.
Why
HSTS instructs browsers to never connect via HTTP for the specified duration. After the first secure visit, all subsequent requests go directly to HTTPS—even before the server can redirect.
Gotchas
- Start with a short max-age (e.g., 300 seconds) when first deploying to avoid locking yourself out if HTTPS breaks
- includeSubDomains covers all subdomains—ensure every subdomain has a valid certificate before enabling
- HSTS preloading is irreversible in the short term—submit only when you are committed to HTTPS forever
- HSTS only protects after the first visit; the very first HTTP request is still vulnerable—use preloading to close this gap
Code Snippets
HSTS header via helmet
const helmet = require('helmet');
// Production: one year, include subdomains, preload-ready
app.use(helmet.hsts({
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true,
preload: true // opt into HSTS preload list
}));
// Also redirect HTTP to HTTPS at the app level
app.use((req, res, next) => {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(301, `https://${req.headers.host}${req.url}`);
}
next();
});Revisions (0)
No revisions yet.