I am trying to create a middleware for Express.js to redirect all non-secure (port 80) traffic to the secured SSL port (443). Unfortunately there is no information in an Express.js request that lets you determine if the request comes over http or https.
One solution would be to redirect every request but this is not an option for me.
Notes:
There is no possibility to handle it with Apache or something else. It has to be done in node.
Only one server can be fired up in the application.
How would you solve that?
Go to the terminal and run the following command. After creation adds key & cert file in your code, and pass the options to the server. const express = require('express'); const https = require('https'); const fs = require('fs'); const port = 3000; var key = fs. readFileSync(__dirname + '/../certs/selfsigned.
We will perform HTTP to HTTPS redirection by creating an Express middleware function [ 1] and then, inside that function, write the redirection code that will force Express to use HTTPS. The middleware function provides access to the Express req and res objects and next function that we will need.
/** * @param req express http request * @returns true if the http request is secure (comes form https) */ function isSecure(req) { if (req. headers['x-forwarded-proto']) { return req. headers['x-forwarded-proto'] === 'https'; } return req. secure; };
Just in case you're hosting on Heroku and just want to redirect to HTTPS regardless of port, here's the middleware solution we're using.
It doesn't bother to redirect if you're developing locally.
function requireHTTPS(req, res, next) { // The 'x-forwarded-proto' check is for Heroku if (!req.secure && req.get('x-forwarded-proto') !== 'https' && process.env.NODE_ENV !== "development") { return res.redirect('https://' + req.get('host') + req.url); } next(); }
You can use it with Express (2.x and 4.x) like so:
app.use(requireHTTPS);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With