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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Behind a load balancer or CDN, you must trust the proxy so req.secure reflects the client's real protocol.
- 2Only safe, idempotent methods (GET/HEAD) should be redirected; other methods should be rejected rather than silently retried over HTTPS.
- 3The HSTS header instructs browsers to use HTTPS on their own, reducing reliance on server-side redirects.
Related explainers
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/enforcing-https-with-express-middleware-explained-javascript-7d6b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.