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
ruby
module Rack class MaintenanceMode RETRY_AFTER = 3600
A Rack maintenance-mode middleware in Rails
middleware
rack
http-status
Intermediate
8 steps
javascript
const express = require('express'); const router = express.Router(); router.get('/articles/:slug', async (req, res, next) => {
Conditional GET caching in Express
http-caching
conditional-get
routing
Intermediate
8 steps
javascript
function parseHexColor(hex) { const cleaned = hex.trim().replace(/^#/, ''); const expand = (short) =>
Parsing hex colors into RGBA channels
parsing
bitwise
regex
Intermediate
7 steps
ruby
module RequestTagging class Middleware def initialize(app) @app = app
Per-request context with CurrentAttributes in Rails
middleware
thread-safety
logging
Intermediate
7 steps
javascript
import { useReducer, useCallback } from 'react'; function historyReducer(state, action) { const { past, present, future } = state;
Undo/redo form state with a React reducer
undo-redo
reducer
immutability
Intermediate
10 steps
php
<?php final class RememberMeCookie {
Signed remember-me cookies in PHP
authentication
hmac
cookies
Intermediate
8 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.