Request local storage handles a particular problem, that of high arity functions in request/response objects and their associated callbacks. Often, to pass data between modules in a web appliation, you have to destructure large options arguments in many functions before the data is actually used, many layers deep in the call stack. For instance, as the author of an express middleware, your middleware is called once on the way in with a request object, then you lose context, and then you are called again with the response object. Generally, you start many asynchronous calls, that might in turn make function calls that take callbacks, and accumulate very long chains of callbacks, such that adding a new parameter to the last callback in the chain requires modifying many functions along the way. Request local storage fixes this by implementing a continuation which reifies the "thread" of execution.
Under the covers, request local storage uses
continuation local storage,
and adds namespaces on top of it to
prevent requests from colliding with each other. CLS keeps track of the number
of listeners that have access to a given continuation by using a proposed node
api called asyncWrap
(implemented with a polyfill),
which is intended to part of the story for how domains
will ultimately be deprecated from node.js. Request
state, then, is stored on process.namespaces
, so that you can access your
request state from any module by require
ing request local storage, which will
then handle registering and deregistering "listeners", or callbacks that should
have access to your namespace, and maintains and retrieves state from its
backing continuation local storage.