Home > Back-end >  node express not executing dynamically added middleware
node express not executing dynamically added middleware

Time:12-09

I am configuring rate-limit in my node express application. I am fetching rate limit configurations from external API and trying to configure the rate-limit middleware or trying to update middleware after getting config data but not getting success.

In app._router.stack, I can see my middleware added but express is not triggering/executing it once I call route/service.

I made one below sample so that you can try to reproduce the problem.

const app = express()

app.get('/', (req, res) => {
  res.send({msg: 'success'})
})

app.listen(4200, () => {
  
  app.use(function testMiddleware (req, res, next) { // this middleware is not executing
    console.log('hello....')
    next()
  })

  console.log(app._router.stack) // above middleware added in stack.
  console.log('Server started successfully!, Open this URL http://localhost:4200')
})

In the above example, It is the same case. If I add middleware after the server start then it is not working. and of course, it is working if I added it before the server started but this is not the case that I am trying to achieve.

Note: I want to add it after the server start. Because fetching config from external API and I have background job that fetches config in 1-5 min and if any changes then apply the setting. All things are automated and don't want to restart the server manually.

CodePudding user response:

It is adding in the stack but the stack is the real problem here. It executes the middleware in the same order which is available in the stack.

// output of console.log(app._router.stack)

Layer {
    handle: [Function: bound dispatch],
    name: 'bound dispatch',
    params: undefined,
    path: undefined,
    keys: [],
    regexp: /^\/?$/i { fast_star: false, fast_slash: false },
    route: Route { path: '/', stack: [Array], methods: [Object] }
  },
  Layer {
    handle: [Function: testMiddleware],
    name: 'testMiddleware',
    params: undefined,
    path: undefined,
    keys: [],
    regexp: /^\/?(?=\/|$)/i { fast_star: false, fast_slash: true },
    route: undefined
  }

It triggers first / routes and there is no next() that is why it is completely unreachable to testMiddleware middleware. If you add next() in / routes body then it will be able to reach middleware but that does not make sense because we need to call middleware first and then route.

so it is creating a new question, how to add dynamic middleware at the top of the route stack and I found something related to https://stackoverflow.com/a/13691542/11286367 https://stackoverflow.com/a/60332223/11286367

CodePudding user response:

You don't call next() on your first middleware, including it fixes the issue.

Could you not also just create the middleware to call a function which is redefined when you want, like so:

const app = require('express')()

var my_func = function(req, res){
  return
}

app.use(function testMiddleware (req, res, next) {
  my_func(req, res)
  next()
})

app.get('/', (req, res, next) => {
  res.send({msg: 'success'})
})

app.listen(4200, () => {
  
  my_func = function(req, res){
    console.log('hello....')
  }

  console.log(app._router.stack)
  console.log('Server started successfully!, Open this URL http://localhost:4200')
})
  • Related