node.jsvariablesauthorizationmiddleware

How to save data in Node JS for a time of request processing?


I want to get the user ID by the passed session ID / auth token in my auth middleware, and then have it available elsewhere after that. How can I do it right, use a global var? Maybe there are better choices?

I think I can pass some object to my middleware to fill it with values, but that does not look nice for me too.


Solution

  • global variable?

    Absolutely not. Multiple requests can be in flight at the same time so using a global or module level variable will conflict between different requests.

    The usual solution is to attach some data to either the req or res object, either as a single property or as an object with multiple properties. This data will then be available to all the rest of the middleware or request handlers that work on this request.

    For example:

    // set a property on the req object
    app.use((req, res, next) => {
        req._startTime = Date.now();
        next();
    });
    
    // use that property on a later request handler for the same request
    app.get("/someroute", (req, res) => {
        console.log("Time of request is", req._startTime);
        res.send("some response");
    });
    

    If you need this value from any other code that is involved in processing the request, then you must pass it as a function argument to that other code from the request handler that calls that other code. There is no "safe" global place to put it where it can just be globally accessed. Remember that in nodejs/Express, multiple requests can be in-flight at the same time. While only one is actually running Javascript at any time, as soon as one request handler "waits" for some asynchronous operation to complete, other request handlers can be run before that prior one completes and thus multiple are in-flight at the same time and you can't safely store state for one request in any global location.