Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force https redirect on heroku with express 4.0?

I don't understand why my following code does not accomplish this? Can someone explain where I am going wrong? All http requests should be redirected to https on heroku, but not on localhost. If someone could point me to an example of this working I would really appreciate it. I feel like this should be very simple and straightforward.

var app = express();

var https_redirect = function () {
  return function(req, res, next) {
    if(process.env.NODE_ENV === 'production'){
      if(req.headers['x-forwarded-proto'] != 'https') {
        return res.redirect('https://' + req.headers.host + req.url);
      } else {
        return next();
      }
    } else {
      return next();
    }
  };
};
app.use(https_redirect());

var server = app.listen(config.port, config.ip, function () {
});

exports = module.exports = app;

I did some searching already and it looks like what I have should work.

like image 501
mikestaub Avatar asked Nov 29 '25 12:11

mikestaub


2 Answers

Your middleware's req, res, next params are being lost by having been wrapped by an outer function.

Try this:

var https_redirect = function(req, res, next) {
    if (process.env.NODE_ENV === 'production') {
        if (req.headers['x-forwarded-proto'] != 'https') {
            return res.redirect('https://' + req.headers.host + req.url);
        } else {
            return next();
        }
    } else {
        return next();
    }
};

app.use(https_redirect);
like image 131
Andrew Lavers Avatar answered Dec 02 '25 01:12

Andrew Lavers


The open source express-force-ssl library checks X-Forwarded-Proto and ought to work with Heroku. The code is very simple.

like image 45
Benjamin Atkin Avatar answered Dec 02 '25 02:12

Benjamin Atkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!