JAVASCRIPT
Enforcing HTTPS with HTTP Strict Transport Security (HSTS) in Node.js
Implement HTTP Strict Transport Security (HSTS) in your Node.js Express application to force clients to use HTTPS, enhancing security against downgrade attacks.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use helmet for general security headers, including HSTS
app.use(helmet.hsts({
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true,
preload: true
}));
// If not using Helmet, you can manually set the header (less recommended):
// app.use((req, res, next) => {
// res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
// next();
// });
// Your routes
app.get('/', (req, res) => {
res.send('Hello HSTS! This page should only be accessible via HTTPS.');
});
// Redirect HTTP to HTTPS (important for HSTS to work effectively on first visit)
app.use((req, res, next) => {
if (req.headers['x-forwarded-proto'] !== 'https' && process.env.NODE_ENV === 'production') {
return res.redirect(['https://', req.get('Host'), req.url].join(''));
}
next();
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
// Note: For HSTS to be effective, your application MUST be served over HTTPS.
// This snippet assumes you have an HTTPS server configured or are behind a proxy
// that handles SSL termination (e.g., Nginx, Load Balancer).
How it works: HTTP Strict Transport Security (HSTS) is a security policy mechanism that helps protect websites against man-in-the-middle attacks, particularly SSL stripping. It forces web browsers to interact with the server only over a secure HTTPS connection. This snippet demonstrates implementing HSTS in an Express.js app using the `helmet` middleware. The `maxAge` parameter tells the browser how long to remember to only connect via HTTPS, `includeSubDomains` applies the policy to subdomains, and `preload` allows for preloading the policy into browsers.