title: routes in nodejs/express get called twice
body: <p>im working in an existing project, and i have a problem driving me insane:</p>
  
  <p>the routes are getting called twice or maybe even more, this happens when any route called take too long to respond</p>
  
  <p>i think the problem is in this file, a dynamic routing attempt</p>
  
  <pre><code>            var express = require('express');
              var recaptcha = require('express-recaptcha');
              //Site key, Secret key
              recaptcha.init('xxxxx', 'yyyyy');
              /**
               * Routes middleware
               * Check all requests
               */
              module.exports = function(app, passport, memoryCache) {
  
                var router = express.Router();
                var config = require('app/config/settings.js');
  
                router.use(function(req, res, next) {
  
                  console.log("touch");
                  console.log(req.url);
                  /**
                   * Make visible req / res on template layout
                   */
                  res.locals.req = req;
                  res.locals.res = res;
                  /**
                   * Url filter
                   */
                  var aryUrl = req.path.split('/').filter(Boolean);
  
                  try {
  
                    var root = '';
                    var controller = '';
                    var controllerPrototype = '';
                    var module = '';
                    var method = '';
                    var url = '';
                    var itemId = '';
                    var privacity = '';
                    var session = '';
  
                    switch (req.originalMethod) {
                      case 'GET':
                        method = 'get';
                        break;
                      case 'POST':
                        method = 'post';
                        break;
                      case 'PUT':
                        method = 'put';
                        break;
                      case 'DELETE':
                        method = 'delete';
                        break;
                    }
  
                    if (aryUrl.length == 0) {
                      root = '/';
                    } else {
                      root = aryUrl[0];
                    }
  
                    switch (root) {
                      case '/':
                        privacity = 'private';
                        session = 'General';
                        module = 'app/controllers/indexController';
                        controller = 'index';
                        controllerPrototype = 'root';
                        url = '/';
  
                        break;
                      case 'index':
                        privacity = 'private';
                        session = 'General';
                        module = 'app/controllers/indexController';
                        controller = 'index';
                        controllerPrototype = aryUrl[1];
                        url = '/index/' + aryUrl[1];
  
                        break;
                      case 'evaluaciones':
                        privacity = 'private';
                        session = 'PortalEval';
                        module = 'app/controllers/view-private/portalEvaluacionController';
                        controller = 'portalEvaluacion';
                        controllerPrototype = 'view';
                        url = '/evaluaciones';
  
                        if (aryUrl.length == 2) {
                            if (aryUrl[1] === 'antesdelcurso' || aryUrl[1] === 'despuesdelcurso') {
                                url = url + '/' + aryUrl[1];
                            } else {
                                controller = '';
                            }
                        }
                        break;
                      case 'relatores':
                          privacity = 'private';
                          session = 'RelatorEval';
                          module = 'app/controllers/portalRelatoresIndexController';
                          controller = 'portalRelatores';
                          controllerPrototype = 'view';
                          url = '/relatores';
                          break;
                      case 'api-pc':
                        privacity = 'public';
                        session = (req.user)? req.user.tipoSession : '';
                        var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
                          return chr.toUpperCase();
                        });
                        ctrl = 'api' + ctrl.charAt(0).toUpperCase() + ctrl.slice(1);
  
                        module = 'app/controllers/api-public/' + ctrl + 'Controller';
                        controller = ctrl;
  
                        if (aryUrl.length == 4) {
                          itemId = '/:id';
                        }
  
                        controllerPrototype = aryUrl[2];
  
                        url = '/api-pc/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
  
                        break;
                      case 'api-pt':
                        privacity = 'private';
                        session = (req.user)? req.user.tipoSession : '';
                        var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
                          return chr.toUpperCase();
                        });
                        ctrl = 'api' + ctrl.charAt(0).toUpperCase() + ctrl.slice(1);
  
                        module = 'app/controllers/api-private/' + ctrl + 'Controller';
                        controller = ctrl;
  
                        if (aryUrl.length == 4) {
                          itemId = '/:id';
                        }
  
                        controllerPrototype = aryUrl[2];
  
                        url = '/api-pt/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
  
                        break;
                      case 'view-pc':
                        privacity = 'public';
                        session = (req.user)? req.user.tipoSession : '';
                        var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
                          return chr.toUpperCase();
                        });
  
                        module = 'app/controllers/view-public/' + ctrl + 'Controller';
                        controller = ctrl;
  
                        if (aryUrl.length == 4) {
                          itemId = '/:id';
                        }
  
                        controllerPrototype = aryUrl[2];
  
                        url = '/view-pc/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
  
                        break;
                      case 'view-pt':
                        privacity = 'private';
                        session = (req.user)? req.user.tipoSession : '';
                        var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
                          return chr.toUpperCase();
                        });
  
                        module = 'app/controllers/view-private/' + ctrl + 'Controller';
                        controller = ctrl;
  
                        if (aryUrl.length == 4) {
                          itemId = '/:id';
                        }
  
                        controllerPrototype = aryUrl[2];
  
                        url = '/view-pt/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
  
                        break;
                      case 'auth':
                        /**
                        * Local Login
                        */
                        var successGetLog = function(req, res) {
                          res.render('login/get.html', {
                            layout: 'layout/auth.html',
                            entorno: config.config_entorno.empresa,
                            message: req.flash('loginMessage'),
                            loginAttempts: req.flash('loginAttempts')
                          });
                        };
  
                        var successPostLog = function (req, res) {
                          var loginAttempts = res.locals.req.user.loginAttempts;
                          if (loginAttempts &gt;= 4){
                            recaptcha.verify(req, function(error){
                              if(error){ //Falla de verificacion de captcha
                                res.render('login/get.html', {
                                  layout: 'layout/auth.html',
                                  entorno: config.config_entorno.empresa,
                                  message: req.flash('loginMessage'),
                                  loginAttempts: loginAttempts,
                                  captcha:recaptcha.render()
                                });
                              } else { //Exito de verificacion de captcha
                                res.redirect('/');
                              }
                            });
                          } else {
                            res.redirect('/');
                          }
                        };
  
                        var successGetLogout = function(req, res) {
                          req.logout();
                          res.redirect('/');
                        };
  
                        router.route('/auth/login').get(successGetLog);
  
                        router.route('/auth/login').post(passport.authenticate("local-login", {failureRedirect: '/auth/logout'}), successPostLog);
  
                        router.route('/auth/logout').get(successGetLogout);
  
                        /**
                        * Encuesta Local Login
                        */
                        var successGetPortalLog = function(req, res) {
                            if (req.query.rut != undefined || req.query.token == 'bciboost') {
                                if (req.query.rut != undefined &amp;&amp; req.query.token == 'bciboost') {
                                    console.log('casi');
                                    req.body = {
                                        rut: req.query.rut,
                                        password: 'null'
                                    };
                                    passport.authenticate('portaleval-link-login', function(err, user, info) {
                                        if (err) {
                                            return next(err);
                                        }
                                        if (!user) {
                                            res.render('portalevaluacionapp/portal_evaluacion_login.html', {
                                                layout: 'layout/empty.html',
                                                entorno: config.config_entorno.empresa,
                                                message: req.flash('loginMessage'),
                                                access: req.path,
                                            });
                                        }
                                        req.logIn(user, function(err) {
                                            if (err) {
                                                return next(err);
                                            }
                                            if (user) {
                                                res.redirect('/evaluaciones');
                                            }
                                        });
                                    })(req, res, next);
                                } else {
                                    res.render('portalevaluacionapp/portal_evaluacion_login.html', {
                                        layout: 'layout/empty.html',
                                        entorno: config.config_entorno.empresa,
                                        message: 'Existe un problema al iniciar sesión',
                                        access: req.path,
                                    });
                                }
                            } else {
                                if (Object.keys(req.session.passport).length !== 0 &amp;&amp; req.session.passport.constructor === Object &amp;&amp; req.path === '/auth/evaluaciones' &amp;&amp; req.session.passport.user.type === 'PortalEval') {
                                    res.redirect('/evaluaciones');
                                } else {
                                    res.render('portalevaluacionapp/portal_evaluacion_login.html', {
                                        layout: 'layout/empty.html',
                                        entorno: config.config_entorno.empresa,
                                        message: req.flash('loginMessage'),
                                        access: req.path,
                                    });
                                };
                            }
                        }
  
                        var successPostPortalLog = function(req, res) {
                          res.redirect(req.path.replace('/auth', ''));
                        };
  
                        var successGetPortalLogout = function(req, res) {
                            req.logout();
                            res.redirect(req.path.replace('/logout', ''));
                        };
  
                        var successGetPortalRelatorLogout = function(req, res) {
                            req.logout();
                            res.redirect("/auth/relatores");
                        };
  
                        if (req.path === '/auth/evaluaciones' || req.path === '/auth/evaluaciones/antesdelcurso' || req.path === '/auth/evaluaciones/despuesdelcurso') {
                          var rutAux = req.body.rut;
                          req.body = {
                              rut: (typeof rutAux === 'undefined' || rutAux === '')? 'null': req.body.rut,
                              password: 'null'
                          };
                        }
  
                        router.route('/auth/evaluaciones').get(successGetPortalLog);
                        router.route('/auth/evaluaciones/antesdelcurso').get(successGetPortalLog);
                        router.route('/auth/evaluaciones/despuesdelcurso').get(successGetPortalLog);
  
                        router.route('/auth/evaluaciones').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);
                        router.route('/auth/evaluaciones/antesdelcurso').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);
                        router.route('/auth/evaluaciones/despuesdelcurso').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);
  
                        router.route('/auth/evaluaciones/logout').get(successGetPortalLogout);
                        router.route('/auth/evaluaciones/logout/antesdelcurso').get(successGetPortalLogout);
                        router.route('/auth/evaluaciones/logout/despuesdelcurso').get(successGetPortalLogout);
  
                        var successGetRelatorLog = function(req, res) {
                            res.render('portalrelatoresapp/portal_relatores_login.html', {
                                layout: 'layout/empty.html',
                                entorno: config.config_entorno.empresa,
                                message: req.flash('loginMessage'),
                                access: req.path,
                            });
                        };
  
  
                        var successPostRelatorPortalLog = function(req, res) {
                          res.redirect(req.path.replace('/auth', ''));
                        };
  
  
  
  
                        router.route('/auth/relatores').get(successGetRelatorLog);
                        router.route('/auth/relatores').post(passport.authenticate("portalrelatores-login", {failureRedirect: '/auth/relatores'}), successPostPortalLog);
                        router.route('/auth/relatores/logout').get(successGetPortalRelatorLogout);
  
  
  
                        break;
                      default:
  
                        break;
                    }
  
                    if (controller != '') {
                      var controllerDynamic = require(module);
  
                      controllerDynamic.req = req;
                      controllerDynamic.res = res;
  
                      /**
                       * Auth validation
                       */
                      if (privacity == 'private') {
                        if (req.isAuthenticated()) {
                          if (session == 'General') {
                            if (controllerDynamic.auth.indexOf('PortalEval') != -1) {
                              var err = new Error(402);
                              throw err;
                            }
                          } else
                          if (session == 'PortalEval') {
                              if (controllerDynamic.auth.indexOf('General') != -1) {
                                  var err = new Error(401);
                                  throw err;
                              }
                          } else
                          if (session == 'RelatorEval') {
                              if (controllerDynamic.auth.indexOf('General') != -1) {
                                  var err = new Error(401);
                                  throw err;
                              }
                          }
              //==============================================================================
                           else
                          if (session == 'PortalRelator') {
                            if (controllerDynamic.auth.indexOf('PortalRelator') == -1) {
                              var err = new Error(402);
                              throw err;
                            }
                          }
              //==============================================================================
                           else {
                              var err = new Error(404);
                              throw err;
                          }
                        } else {
                          if (controllerDynamic.auth.indexOf('PortalEval') != -1) {
                              var err = new Error(402);
                              throw err;
                          } else
                          if (controllerDynamic.auth.indexOf('General') != -1) {
                              var err = new Error(401);
                              throw err;
                          } else {
                              var err = new Error(404);
                              throw err;
                          }
                        }
                      }
  
                      /**
                       * Check the "auth" atribute of a controller
                       */
                      // if (controllerDynamic.auth.indexOf(controllerPrototype) != -1) {
  
                      // }
  
                      /**
                       * Final validation
                       */
                      var isValid = true;
                      if (aryUrl.length &gt; 4) {
                        isValid = false;
                      }
  
                      if (method == '') {
                        isValid = false;
                      }
  
                      if (typeof controllerDynamic[controllerPrototype] !== "function") {
                        isValid = false;
                      }
  
                      if (isValid) {
                          router.route(url)[method](function(ctrlReq, ctrlRes){
                              controllerDynamic[controllerPrototype](ctrlReq, ctrlRes);
                          });
                      } else {
                        res.status(404).send('Not found');
                   }
                    }
  
                    next();
  
                  } catch (e) {
                    if (e.message == 401) {
                      res.status(401).redirect('/auth/login');
                    } else
                    if (e.message == 402) {
                      res.status(401).redirect('/auth' + url);
                    } else {
                      res.status(404).send('Not found 2');
                    }
                  }
                });
  
                app.use('/', router);
              };
  </code></pre>
  
  <p>in fact that console.log(touch) get called twice if the route doesn't respond fast (in less than 8 minutes) i had no idea what is going on</p>
  
  <p>Thanks guys!</p>