JAVASCRIPT

Enforcing HTTPS with HSTS (HTTP Strict Transport Security)

Implement HTTP Strict Transport Security (HSTS) in Node.js Express to enforce HTTPS, protecting against protocol downgrade attacks and cookie hijacking.

const express = require('express');
const app = express();

// IMPORTANT: HSTS should ONLY be applied after verifying that your entire site
// and all subdomains are capable of serving content over HTTPS exclusively.
// Once HSTS is set, browsers will refuse to connect via HTTP for the specified duration.

app.use((req, res, next) => {
  if (req.secure || req.get('x-forwarded-proto') === 'https') {
    // Only set HSTS header if the request is already secure (HTTPS)
    // 'x-forwarded-proto' check is for apps behind a reverse proxy/load balancer
    res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
  }
  next();
});

// Middleware to redirect HTTP to HTTPS (for initial unsecured requests)
app.use((req, res, next) => {
  if (!req.secure && req.get('x-forwarded-proto') !== 'https') {
    // Redirect HTTP to HTTPS in production behind a proxy (e.g., Nginx, Heroku)
    // Adjust 'x-forwarded-proto' check based on your proxy configuration
    return res.redirect('https://' + req.headers.host + req.url);
  }
  next();
});

app.get('/', (req, res) => {
  res.send('<h1>This site enforces HTTPS!</h1><p>Check your network tab for the HSTS header.</p>');
});

const PORT = process.env.PORT || 3000;
// In production, Express should listen on HTTP for a reverse proxy
// or directly on HTTPS if no proxy is used.
// For this example, we simulate with HTTP and redirect.
app.listen(PORT, () => console.log(`Server running on port ${PORT}. Try accessing via HTTP first, then HTTPS.`));
How it works: This Node.js Express snippet demonstrates how to implement HTTP Strict Transport Security (HSTS). HSTS is a security policy mechanism that helps protect websites against downgrade attacks and cookie hijacking by forcing web browsers to interact with it using only HTTPS connections. Once a browser receives the `Strict-Transport-Security` header, it will automatically convert all future HTTP requests for that domain (and optionally subdomains) to HTTPS for the specified `max-age` duration, even if the user explicitly types `http://`. The snippet also includes a redirect from HTTP to HTTPS for initial visits.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs