Search code examples
javascriptnode.jsexpressmiddleware

Middleware function is executed multiple times rather than just once when using dynamic routes


I have this middleware:

app.use((req, res, next) => {
  console.log('test');
  next();
});

and I have these dynamic routes:

app.get('/:path', (req, res, next) =>{
  var pages = serverCache.pages;
  for (let page of pages) {
    if(req.params.path === page.path){
      res.render('foo', {
        helpers:helpers
      });
      return;
    }//if
  }//for
  res.redirect('/');
});

When a page is loaded I would expect execution of console.log('test') only once. However it is executed many times. Actual output is:

test
test
test
test
...

It happens because it is executed for each iteration inside for loop. How do I execute it only when if statement criteria inside that loop is true ?


Solution

  • I misunderstood when would function be executed.

    The reason why it was executed multiple times is because it executes itself for each route it checks. (For all middleware functions afterwards)

    For it to execute only for my dynamic routes, I moved both of these function to the bottom.

    app.get('static route')
    app.post('static route')
    app.use('static route')
    app.use(); // moved it here
    app.get('dynamic route')