Node.js Force SSL in production

Have you tried enforcing https for your app in Node?

Having researched(googled) innumerable solutions what failed for us initially were the checks for 

  • req.secure
  • req.protocol
  • req.connection.encrypted

None of those were reliable.

However the check for header value x-forwarded-proto was also somehow reliable for us.

Try pasting the following in your app.js or server.js and see if it works

function requireHTTPS(req, res, next) {
  if (req.headers['x-forwarded-proto'] == 'https') {
    return next();
  } else {
    res.redirect('https://' + req.headers.host + req.path);
  }
}
if (app.get('env') != 'development') app.use(requireHTTPS);

Message from Sponsor: Checkout Node.js jobs in Los Angeles, CA