This is 2016 and there is no excuse to still using http.
Because your visitors will often type your domain directly in the address bar of their browser (e.g.
mako.ai) without explicitely appending
https:// you will have to redirect them to https.
This particular example assumes that your are serving AngularJS or any other kind of SPA framework hosted on heroku, but it should work on more generally with any type of express based set up.
web.js use the following:
var express = require('express');
The magic happens in this bit:
req.headers['x-forwarded-proto'] should be equal to
In addition, when testing our code locally we don’t want to trigger the redirect since we don’t have a ssl certificate set up on localhost. Therefore we also use
process.env.NODE_ENV === 'production' inside the condition to make sure that this will only run on Heroku, which has the
NODE_ENV environment variable set to
If both these conditions are met, this means someone is trying to access our app though http. We need to swap http for https and redirect them to the new url. To reconstruct the url that they are trying to call we use
req.hostname in combination with
And finally we redirect using