How to force SSL / https in Express.js


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.


  1. There is no possibility to handle it with Apache or something else. It has to be done in node.

  2. Only one server can be fired up in the application.

How would you solve that?

12/6/2015 4:45:10 AM

Accepted Answer

Since I was working on nginx, I had access to the header's x-forwarded-proto property so I could write a tiny middleware to redirect all traffic as described here:

Edit: Updated the url

3/14/2012 11:51:02 AM

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.get('x-forwarded-proto') !== 'https' && process.env.NODE_ENV !== "development") {
    return res.redirect('https://' + req.get('host') + req.url);

You can use it with Express (2.x and 4.x) like so:


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow