Node Domains.
This is an old question, I understand this, but none of the answers are completely correct.
In truth, you can achieve this functionality using Node Domains.
Global variables are generally considered bad to use because they break encapsulation, and a properly encapsulated application is the first building block for good design because it will make it easier to read, test, and refactor.
As I said, I personally came across many good examples of using global variables within a single query.
Example Tracking a single request through many levels of code becomes impossible without this, unless you expose your request (or req ID) to layers to which it simply does not belong. (i.e. Service, DAL, etc ... save your request in the controller, if it belongs).
In principle, passing variables through many layers just to be available at lower levels of my application is unstable and makes the code very dirty.
Before you start screaming, yes, I know that domains are deprecated from Node 5, and I also know that this is not an exact precedent for domains, as it is documented. But Node is finalizing a new API, which we hope will continue to solve this problem.
https://nodejs.org/api/domain.html
source share