If you want to preserve the data across the async callback and there could be scenarios, where request and response objects are not available. So in that case continuation-local-storage package, is helpful.
It is used to access the data or the current express request/response from a point where that is not readily accessible. It use the concept of namespace.
Here is how I set up this
Install the continuation-local-storage
package
npm install continuation-local-storage --save
Create namespace
let app = express();
let cls = require('continuation-local-storage');
let namespace = cls.createNamespace('com.domain');
then middleware
app.use((req, res, next) => {
var namespace = cls.getNamespace('com.domain');
// wrap the events from request and response
namespace.bindEmitter(req);
namespace.bindEmitter(res);
// run following middleware in the scope of the namespace we created
namespace.run(function () {
// set data on the namespace, makes it available for all continuations
namespace.set('data', "any_data");
next();
});
})
Now in any file or function you can get this namespace and use the saved data in it
//logger.ts
var getNamespace = require("continuation-local-storage").getNamespace;
let namespace = getNamespace("com.domain");
let data = namespace.get("data");
console.log("data : ", data);