Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs AsyncLocalStorage getStore() return undefined

I read this post AsyncLocalStorage for Easy Context Passing in Node.js I try to get logId in my logs, but i cant, beacause asyncLocalStorage.getStore() return undefined. It seems that context was lost inside MyLogger class. How to solve it?

Here is my express App

  const asyncLocalStorage = new AsyncLocalStorage();

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

Here is MyLogger class

   static log(logId, className, text) {
    const { asyncLocalStorage } = require("../server.js");
    const store = asyncLocalStorage.getStore()
    console.log(this._getBaseStaticLog(logId, logTypes.LOG, text, className));
  }
like image 635
Masquitos Avatar asked Apr 09 '26 04:04

Masquitos


1 Answers

I solve the problem. The problem was that i lose context due to bodyparser middleware. I change that middleware before set context, and now its ok. Was:

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

// body parser
app.use(
  bodyParser.json({
    limit: "10mb"
  })
);

Change:

// body parser
app.use(
  bodyParser.json({
    limit: "10mb"
  })
);

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

And now its ok)

like image 142
Masquitos Avatar answered Apr 10 '26 16:04

Masquitos