I\'m using Express and I need to access some data that it is on the request (headers, cookies, etc) every time I use the log to debug and trace my app.
With other langu
Have a look at Continuation Local Storage, it implements something similar to thread context for asynchronous call chains: https://github.com/othiym23/node-continuation-local-storage
Also there are efforts to build asynchronous local storage as a standardized feature into javascript itself, but they are still at a very early stage: TC39 Zone Proposal https://docs.google.com/presentation/d/1H3E2ToJ8VHgZS8eS6bRv-vg5OksObj5wv6gyzJJwOK0
The fact that JavaScript is single threaded is not a limitation and doesn't prevent using "Thread Context" as a means to use "universally accessible state". The problems will start as soon as asynchronous calls are made and the state no longer matches what you intend it to be.
This is one of the reasons why global state is considered "bad habit" and you should aim to avoid it (not specifically when developing in JavaScript and/or Node...).
Instead, you should pass around an object, but not req
. You should construct your objects or call your functions in such a way that the log
instance that's relevant to every call chain (starting at the request event and through all internal calls) is passed around. That log
instance should be initialized with whatever context of required for logging, and in your case, the request details from the original req
.