javascript 34 lines · 6 steps

Enforcing HTTPS with Express middleware

A middleware chain that trusts a proxy, sets HSTS, and redirects or rejects insecure requests.

Explained by highlit
1const express = require('express');
2 
3const app = express();
4 
5app.set('trust proxy', 1);
6 
7const enforceHttps = (req, res, next) => {
8 if (req.secure) {
9 return next();
10 }
11 
12 if (req.method === 'GET' || req.method === 'HEAD') {
13 const host = req.headers.host;
14 return res.redirect(301, `https://${host}${req.originalUrl}`);
15 }
16 
17 return res.status(403).json({
18 error: 'HTTPS is required for this request.',
19 });
20};
21 
22app.use((req, res, next) => {
23 res.setHeader(
24 'Strict-Transport-Security',
25 'max-age=63072000; includeSubDomains; preload'
26 );
27 next();
28});
29 
30if (process.env.NODE_ENV === 'production') {
31 app.use(enforceHttps);
32}
33 
34module.exports = { app, enforceHttps };
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Behind a load balancer or CDN, you must trust the proxy so req.secure reflects the client's real protocol.
  2. 2Only safe, idempotent methods (GET/HEAD) should be redirected; other methods should be rejected rather than silently retried over HTTPS.
  3. 3The HSTS header instructs browsers to use HTTPS on their own, reducing reliance on server-side redirects.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Enforcing HTTPS with Express middleware — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code