How to force SSL / https in Express.js


Question

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:

  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?

1
55
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: http://elias.kg/post/14971446990/force-ssl-with-express-js-on-heroku-nginx

Edit: Updated the url

-1
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.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);

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