title: Express.js redirect loop - Production Only
body: <p>I am running an app with separated API and Front, both running on Express.js.</p>
  
  <p>I have created a redirect on API to redirect '/' and missing routes to frontend URL. 
  Everything works on dev, however, <strong>I get a redirect loop - ERR_TOO_MANY_REDIRECTS error on production</strong>.
  Production is working on <strong>https</strong>, so I am not sure if that could be the problem, and <strong>I am using Helmet package for security</strong>.</p>
  
  <p>Tried to create 2 solutions and searched through SO, but none work:</p>
  
  <p>-----  #1 - app.js ----- </p>
  
  <pre><code>// catch 404 and forward to error handler
  app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
  });
  
  // error handler
  app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
  
    //log error   
    logging.error(err);
    res.status(err.status || 500);
  
    // frontUrl is http://xx.com for dev, and https://xy.com for production
    res.redirect(frontUrl);
  });
  
  module.exports = app;
  </code></pre>
  
  <p>----- #2 - app.js ----- </p>
  
  <pre><code>// error handler
  app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
  
    //log error   
    logging.error(err);
    res.status(err.status || 500);
  
  res.redirect('/');
  });
  
  module.exports = app;
  </code></pre>
  
  <p>-----  /routes/index.js ----- </p>
  
  <pre><code>var frontUrl = require('../config.json').FrontURL;
  
  router.get('/', function(req, res, next) {
      res.redirect(frontUrl);
  });
  </code></pre>