JAVASCRIPT
Enforce HTTPS with HTTP Strict Transport Security (HSTS) Header
Implement the HTTP Strict Transport Security (HSTS) header in your Node.js Express application using Helmet to automatically force browsers to use secure HTTPS connections.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use Helmet to set various security headers
app.use(helmet());
// Configure and apply HSTS middleware
app.use(helmet.hsts({
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true, // Apply to subdomains as well
preload: true // Opt-in to browser preload lists (requires strict maxAge and includeSubDomains)
}));
// Example route
app.get('/', (req, res) => {
res.send('This page is served with HSTS enforced!');
});
// Redirect HTTP to HTTPS in a production environment (optional, but recommended)
app.use((req, res, next) => {
if (process.env.NODE_ENV === 'production' && !req.secure) {
// req.hostname might include port, use it if not using a proxy that strips it
// Or configure your proxy (e.g., Nginx) to handle this redirection
return res.redirect('https://' + req.headers.host + req.url);
}
next();
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT} (ensure you're using HTTPS for HSTS to take effect).`);
});
How it works: This snippet demonstrates how to implement the HTTP Strict Transport Security (HSTS) header in an Express.js application using the `helmet` middleware. HSTS instructs web browsers to only interact with your site using HTTPS, even if the user explicitly types HTTP or follows an HTTP link. This prevents common downgrade attacks and cookie hijacking. The `maxAge` parameter defines how long the browser should remember this policy, `includeSubDomains` extends it to subdomains, and `preload` allows inclusion in browser HSTS preload lists for enhanced security.