Express HTTP to HTTPS Redirect Middleware

1.1.4 · abandoned · verified Wed Apr 22

express-http-to-https is a lightweight Node.js package designed to provide an Express.js middleware for automatically redirecting HTTP traffic to HTTPS. This utility focuses on a single concern: ensuring that clients attempting to connect over unencrypted HTTP are seamlessly redirected to the secure HTTPS version of the application. The current stable version is 1.1.4, but the package has not seen active development in approximately eight years, with its last publish occurring in April 2018, indicating it is largely abandoned. Key differentiators include its simplicity and configurable options to ignore specific hostnames (e.g., for local development) or routes, as well as the ability to specify the HTTP redirect status code. It relies on checking the `x-forwarded-proto` header, which is standard when running applications behind a reverse proxy like Nginx or a cloud load balancer. While functional for its core purpose, its lack of recent updates means it might not incorporate modern Express or Node.js features, nor receive security patches.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to apply the `redirectToHTTPS` middleware to an Express application, showing configuration for ignoring specific hosts and routes, and explicitly enabling 'trust proxy' for deployments behind reverse proxies.

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

var redirectToHTTPS = require('express-http-to-https').redirectToHTTPS;

// Important: Enable 'trust proxy' if running behind a reverse proxy (e.g., Nginx, Heroku, AWS ELB).
// This allows Express to correctly interpret 'x-forwarded-proto' headers.
app.enable('trust proxy');

// Don't redirect if the hostname is `localhost:port` or the route is `/insecure`
app.use(redirectToHTTPS([/localhost:(\d{4})/], [//insecure/], 301));

app.get('/', function (req, res) {
  res.send('Hello World - Secure!');
});

app.get('/insecure', function (req, res) {
  res.send('Dangerous - Insecure Route!');
});

// Listen on HTTP for demonstration of redirect
app.listen(3000, function () {
  console.log('HTTP server listening on port 3000 (will redirect to HTTPS if not ignored)!');
});

// In a real application, you would also run an HTTPS server on port 443
// const https = require('https');
// const fs = require('fs');
// const options = {
//   key: fs.readFileSync('path/to/your/private.key'),
//   cert: fs.readFileSync('path/to/your/certificate.crt')
// };
// https.createServer(options, app).listen(443, function () {
//   console.log('HTTPS server listening on port 443!');
// });

view raw JSON →