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.
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);
The open source express-force-ssl library checks X-Forwarded-Proto and ought to work with Heroku. The code is very simple.
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