How to force SSL / https in Express.js

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

Leave a Comment