Force SSL with MEAN.JS on Heroku
Working on MEAN.JS platform and using it with Heroku is a real pleasure. It’s not very common that you have to configure something. During one of my startup projects, I’ve had opportunity to solve one such situation. Let’s start with the problem.
The problem
Heroku offers great opportunities for all of us working with SSL/HTTPS. But if you are using MEAN.JS on Heroku, you might have a problem if you want to redirect all users visiting on HTTP to HTTPS. Thus, you have to configure automatic redirect in such scenarios. And it might be tricky.
Actually, automatic redirect on MEAN.JS middleware is quite simple. Just check for the secure property in the request object. If it’s true everything’s fine, user is visiting on HTTPS, and if it’s false you can redirect them. Alas, it’s not like that on Heroku. Due to internal way how Heroku works, this flag is not set. So what’s our option?
The solution
Actually, quite simple. In this case, you can check request.header and check if x-forwarded-proto is set and what’s the actual value: http or https. In case it’s http, we should redirect, but how we can do it on MEAN.JS.
Fire up your favorite text editor, open your solution, check few things, change a couple of lines and you are ready to go! Let’s go.
Go to config / lib / express.js. Add following function:
function forceSsl(req, res, next) {
if (!req.secure && req.get(‘x-forwarded-proto’) !== ‘https’ && process.env.NODE_ENV === ‘production’) {
return res.redirect(‘https://’ + req.get(‘host’) + req.url);
}
next();
}
Note: we are using NODE_ENV to indicate if we are working on production or test, if you are working different and didn’t set up this flag on Heroku, remove last part of expression in if statement.
Finally, we have to call our function. We can do it from initMiddleware like this:
app.use(forceSsl);
That’s it! Build, deploy. Go ahead and try it. Happy coding 🙂