Heroku NodeJS http to https ssl forced redirect

heroku, https, node.js, redirect, ssl

Solution

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.

Problem

I have an application up and running on Heroku with Express.js on Node.js with `https`. How do I identify the protocol to force a redirect to `https` with Node.js 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); ```

Original source