Samuel Josh
Samuel Josh

Reputation: 37

How does next function work in node js async localstorage middleware

I am creating a middleware for adding trace id to each req and come across async hook and async localstorage, but I am confused about why next function is passed inside the run method, and when I remove the next function and move it outside the run function the middleware does not work as expected so can someone please explain to me what does putting next() inside run() is doing to make things work. Below is the code sample-

app.use((req, res, next) => {
  asyncLocalStorage.run(new Map(), () => {
    asyncLocalStorage.getStore().set("requestId", uuid());
    next();
  });
});

Upvotes: 3

Views: 1031

Answers (1)

robertklep
robertklep

Reputation: 203329

If you place next() outside the callback, it will not be run within the context created by asyncLocalStorage and (hence) you won't be able to access the store.

This is also explained in the documentation:

The store is not accessible outside of the callback function. The store is accessible to any asynchronous operations created within the callback.

Upvotes: 1

Related Questions