Let's say I have a variable, x
, which is set on the request req.x
in an express middleware. We can expose this to client through the template, <%- window.x = req.x %>
.
I would now like to use this variable globally. On client, we can use x
directly since it's in the window context. But on the server, how do we do the same if there is no window or global context?
We can't set it on globals
object in Node because that really global, not global to the request.
There is no such thing as global to a request. Because there can be many requests in flight at once in node.js, there is no place to store something that is global to a request other than on the request object itself.
So, the usual solution here (and the general OO way of doing things) is to just pass the request object to anything that needs request-specific state. Then those functions can access whatever state is desired on the request object.
You can manufacture some sort of global store lookup that would allow you to store something globally and then be able to look it up given some key (such as a userID for a given request or some cookie value for a given request). This is basically how persistent session data is stored. But, if you're trying to access data that is specific to a user or to a request, you're going to have to pass something along to any function that needs that info that can be used as a key to look up the right data in the global store because there can be many requests active at a time.
While node.js is largely single threaded, any time you make any sort of async call in a request handler (reading asynchronously from the disk or doing networking or setting a timer), then other requests get a chance to start running and many can be in flight at the same time. Thus, there is no way to associate generic global state with any given request.
The usual way to solve this is to just pass this state along to other functions that might need it:
app.get("somepath", function(req, res) {
callSomeFunc(req);
});
function callSomeFunc(request) {
callSomeOtherFunc(request);
}
function callSomeOtherFunc(r) {
// access request info from the r argument here
}