JAVASCRIPT
Implementing HTTP Strict Transport Security (HSTS) in Express.js
Enforce HTTPS for your Express.js application by implementing the HSTS header, ensuring secure connections and protecting against downgrade attacks.
const express = require('express');
const helmet = require('helmet'); // Helmet helps secure Express apps by setting various HTTP headers
const app = express();
// Use Helmet to set security-related HTTP headers
// Helmet includes 'hsts' by default, but we can configure it explicitly.
app.use(helmet({
hsts: {
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true,
preload: true
}
}));
app.get('/', (req, res) => {
res.send('Hello HSTS! This page should only be accessed via HTTPS.');
});
// Note: HSTS header is only sent over HTTPS connections.
// Ensure your server is configured to run on HTTPS for HSTS to be effective.
// For development, you might run HTTP, but for production, you need HTTPS.
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log('Remember to use HTTPS for HSTS to be effective in production.');
});
How it works: HTTP Strict Transport Security (HSTS) is a security policy mechanism that helps protect websites against downgrade attacks and cookie hijacking. This Express.js snippet uses the 'helmet' middleware to easily implement HSTS. By setting `maxAge` to a long duration (e.g., one year), `includeSubDomains` to true, and `preload` to true, you instruct browsers to only connect to your site using HTTPS, even if the user explicitly types 'http://'.