Redirected you too many times - Express/node on Heroku

Viewed 922

Using Express/node on Heroku I get an error: Redirected you too many times or net::ERR_TOO_MANY_REDIRECTS in the console.

I'm new to Express and I tried to add a redirect so all http requests on my two custom domains get redirected to https. This is what's breaking the site. If any has ideas to fix it that would be amazing!

var express = require('express');
const path = require('path');

var app = express();

// process.env.PORT gets the port for Heroku or goes to 3000
const PORT = process.env.PORT || 3000;

app.enable('trust proxy');

// in production on Heroku - re-route everything to https
if (process.env.NODE_ENV==="production") {
  app.use((req, res, next) => {
    if (req.header['x-forwarded-proto'] !== 'https') {
      res.redirect('https://' + req.hostname + req.url);
    } else {
      next()
    }
  })
}

app.use(express.static(path.join(__dirname, '/public')));

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'public/index.html'));
});

app.listen(PORT, function() {
  console.log('Express server is up on port:' + PORT);
});
1 Answers
Related