Heroku NodeJS http to https ssl forced redirect

RedirectSslnode.jsHttpsHeroku

Redirect Problem Overview


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);

Redirect Solutions


Solution 1 - Redirect

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']

Solution 2 - Redirect

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.

Solution 3 - Redirect

The accepted answer has a hardcoded domain in it, which isn't too good if you have the same code on several domains (eg: dev-yourapp.com, test-yourapp.com, yourapp.com).

Use this instead:

/* Redirect http to https */
app.get("*", function (req, res, next) {

	if ("https" !== req.headers["x-forwarded-proto"] && "production" === process.env.NODE_ENV) {
		res.redirect("https://" + req.hostname + req.url);
	} else {
		// Continue to other routes if we're not redirecting
		next();
	}

});

https://blog.mako.ai/2016/03/30/redirect-http-to-https-on-heroku-and-node-generally/

Solution 4 - Redirect

I've written a small node module that enforces SSL on express projects. It works both in standard situations and in case of reverse proxies (Heroku, nodejitsu, etc.)

https://github.com/florianheinemann/express-sslify

Solution 5 - Redirect

If you want to test out the x-forwarded-proto header on your localhost, you can use nginx to setup a vhost file that proxies all of the requests to your node app. Your nginx vhost config file might look like this

NginX
server {
  listen 80;
  listen 443;
  
  server_name dummy.com;

  ssl on;
  ssl_certificate     /absolute/path/to/public.pem;
  ssl_certificate_key /absolute/path/to/private.pem;
  
  access_log /var/log/nginx/dummy-access.log;
  error_log /var/log/nginx/dummy-error.log debug;

  # node
  location / {
    proxy_pass http://127.0.0.1:3000/;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
  }
}

The important bits here are that you are proxying all requests to localhost port 3000 (this is where your node app is running) and you are setting up a bunch of headers including X-Forwarded-Proto

Then in your app detect that header as usual

Express
var app = express()
  .use(function (req, res, next) {
    if (req.header('x-forwarded-proto') == 'http') {
      res.redirect(301, 'https://' + 'dummy.com' + req.url)
      return
    }
    next()
  })
Koa
var app = koa()
app.use(function* (next) {
  if (this.request.headers['x-forwarded-proto'] == 'http') {
    this.response.redirect('https://' + 'dummy.com' + this.request.url)
    return
  }
  yield next
})
Hosts

Finally you have to add this line to your hosts file

127.0.0.1 dummy.com

Solution 6 - Redirect

You should take a look at heroku-ssl-redirect. It works like a charm!

var sslRedirect = require('heroku-ssl-redirect');
var express = require('express');
var app = express();

// enable ssl redirect
app.use(sslRedirect());

app.get('/', function(req, res){
  res.send('hello world');
});

app.listen(3000);

Solution 7 - Redirect

If you are using cloudflare.com as CDN in combination with heroku, you can enable automatic ssl redirect within cloudflare easily like this:

  1. Login and go to your dashboard

  2. Select Page Rules

Select Page Rules 3. Add your domain, e.g. www.example.com and switch always use https to on Switch always use https to on

Solution 8 - Redirect

Loopback users can use a slightly adapted version of arcseldon answer as middleware:

server/middleware/forcessl.js

module.exports = function() {  
  return function forceSSL(req, res, next) {
    var FORCE_HTTPS = process.env.FORCE_HTTPS || false;
      if (req.headers['x-forwarded-proto'] !== 'https' && FORCE_HTTPS) {
        return res.redirect(['https://', req.get('Host'), req.url].join(''));
      }
      next();
    };
 };

server/server.js

var forceSSL = require('./middleware/forcessl.js');
app.use(forceSSL());

Solution 9 - Redirect

This is a more Express specific way to do this.

app.enable('trust proxy');
app.use('*', (req, res, next) => {
  if (req.secure) {
    return next();
  }
  res.redirect(`https://${req.hostname}${req.url}`);
});

Solution 10 - Redirect

I am using Vue, Heroku and had same problem :

I updated my server.js as below, and i am not touching it anymore because it is working :) :

const serveStatic = require('serve-static')
const sts = require('strict-transport-security');
const path = require('path')

var express = require("express");

require("dotenv").config();
var history = require("connect-history-api-fallback");

const app = express()
const globalSTS = sts.getSTS({'max-age':{'days': 365}});
app.use(globalSTS);

app.use(
  history({
    verbose: true
  })
);

app.use((req, res, next) => {
  if (req.header('x-forwarded-proto') !== 'https') {
    res.redirect(`https://${req.header('host')}${req.url}`)
  } else {
    next();
  }
});

app.use('/', serveStatic(path.join(__dirname, '/dist')));
app.get(/.*/, function (req, res) {
res.sendFile(path.join(__dirname, '/dist/index.html'))
})

const port = process.env.PORT || 8080
app.listen(port)
console.log(`app is listening on port: ${port}`)

Solution 11 - Redirect

app.all('*',function(req,res,next){
  if(req.headers['x-forwarded-proto']!='https') {
    res.redirect(`https://${req.get('host')}`+req.url);
  } else {
    next(); /* Continue to other routes if we're not redirecting */
  }
});

Solution 12 - Redirect

With app.use and dynamic url. Works both localy and on Heroku for me

app.use(function (req, res, next) {
  if (req.header('x-forwarded-proto') === 'http') {
    res.redirect(301, 'https://' + req.hostname + req.url);
    return
  }
  next()
});

Solution 13 - Redirect

Checking the protocol in the X-Forwarded-Proto header works fine on Heroku, just like Derek has pointed out. For what it's worth, here is a gist of the Express middleware that I use and its corresponding test.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDerek BredensteinerView Question on Stackoverflow
Solution 1 - RedirectarcseldonView Answer on Stackoverflow
Solution 2 - RedirectDerek BredensteinerView Answer on Stackoverflow
Solution 3 - RedirectJoan-Diego RodriguezView Answer on Stackoverflow
Solution 4 - RedirectflorianView Answer on Stackoverflow
Solution 5 - RedirectsimoView Answer on Stackoverflow
Solution 6 - RedirectJulien Le CoupanecView Answer on Stackoverflow
Solution 7 - Redirectelectronix384128View Answer on Stackoverflow
Solution 8 - RedirectBunkerView Answer on Stackoverflow
Solution 9 - RedirectdenixtryView Answer on Stackoverflow
Solution 10 - RedirectShirish SinghView Answer on Stackoverflow
Solution 11 - RedirectChiedoView Answer on Stackoverflow
Solution 12 - RedirecttuancharlieView Answer on Stackoverflow
Solution 13 - RedirectPeter MarklundView Answer on Stackoverflow