Common HSTS Implementation Mistakes
Common HSTS Implementation Mistakes
Mistake 1: Setting HSTS on HTTP responses
// Wrong - HSTS on HTTP
app.use((req, res, next) => {
res.setHeader('Strict-Transport-Security', 'max-age=31536000');
next();
});
// Correct - Only on HTTPS
app.use((req, res, next) => {
if (req.secure || req.headers['x-forwarded-proto'] === 'https') {
res.setHeader('Strict-Transport-Security', 'max-age=31536000');
}
next();
});
Mistake 2: Not considering subdomain impact
// Careful with includeSubDomains
// Ensure all subdomains support HTTPS before enabling
const subdomainReadiness = {
'www.example.com': true,
'api.example.com': true,
'legacy.example.com': false // Still on HTTP
};
const allSubdomainsReady = Object.values(subdomainReadiness).every(ready => ready);
const hstsDirective = allSubdomainsReady
? 'max-age=31536000; includeSubDomains'
: 'max-age=31536000';