Heroku NodeJS http to https ssl forced redirect


Question

I have an application up and running on heroku with express on node with https,. How do I identify the protocol to force a redirect to https with nodejs on heroku?

My app is just a simple http server, it doesn't (yet) realize heroku is sending it https requests:

/* Heroku provides the port they want you on in this environment variable (hint: it's not 80) */
app.listen(process.env.PORT || 3000);
1
99
8/25/2011 4:15:46 AM

Accepted Answer

The answer is to use the header of 'x-forwarded-proto' that Heroku passes forward as it does it's proxy thingamabob. (side note: They pass several other x- variables too that may be handy, check them out).

My code:

/* At the top, with other redirect methods before other routes */
app.get('*',function(req,res,next){
  if(req.headers['x-forwarded-proto']!='https')
    res.redirect('https://mypreferreddomain.com'+req.url)
  else
    next() /* Continue to other routes if we're not redirecting */
})

Thanks Brandon, was just waiting for that 6 hour delay thing that wouldn't let me answer my own question.

93
1/3/2013 1:57:56 PM

As of today, 10th October 2014, using Heroku Cedar stack, and ExpressJS ~3.4.4, here is a working set of code.

The main thing to remember here is that we ARE deploying to Heroku. SSL termination happens at the load balancer, before encrypted traffic reaches your node app. It is possible to test whether https was used to make the request with req.headers['x-forwarded-proto'] === 'https'.

We don't need to concern ourselves with having local SSL certificates inside the app etc as you might if hosting in other environments. However, you should get a SSL Add-On applied via Heroku Add-ons first if using your own certificate, sub-domains etc.

Then just add the following to do the redirect from anything other than HTTPS to HTTPS. This is very close to the accepted answer above, but:

  1. Ensures you use "app.use" (for all actions, not just get)
  2. Explicitly externalises the forceSsl logic into a declared function
  3. Does not use '*' with "app.use" - this actually failed when I tested it.
  4. Here, I only want SSL in production. (Change as suits your needs)

Code:

 var express = require('express'),
   env = process.env.NODE_ENV || 'development';

 var forceSsl = function (req, res, next) {
    if (req.headers['x-forwarded-proto'] !== 'https') {
        return res.redirect(['https://', req.get('Host'), req.url].join(''));
    }
    return next();
 };

 app.configure(function () {

    if (env === 'production') {
        app.use(forceSsl);
    }

    // other configurations etc for express go here...
}

Note for SailsJS (0.10.x) users. You can simply create a policy (enforceSsl.js) inside api/policies:

module.exports = function (req, res, next) {
  'use strict';
  if ((req.headers['x-forwarded-proto'] !== 'https') && (process.env.NODE_ENV === 'production')) {
    return res.redirect([
      'https://',
      req.get('Host'),
      req.url
    ].join(''));
  } else {
    next();
  }
};

Then reference from config/policies.js along with any other policies, e.g:

'*': ['authenticated', 'enforceSsl']


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon