Flion
Flion

Reputation: 10892

Retreive session information in nodejs / express without request variable

If I use express-session the session variable becomes available under req.session in for example:

 app.get('/', function(req, res) {
      req.session.myVar = 1;
 }

But what if I want to retreive the session of the current request deeply nested in my application where I do not have the req variable available?

Is there another way besides passing in the req variable as a parameter all across the framework?

Upvotes: 2

Views: 1993

Answers (2)

Flion
Flion

Reputation: 10892

The solution for me was to use Continuation-local-storage as middleware for express like outlined in this question as well NodeJS TransactionID with Continuation-local-storage

    import * as cls from "continuation-local-storage";

    cls.createNamespace('mynamespace');
    app.use((req, res, next) => {
        let session = cls.getNamespace('mynamespace');
        session.bindEmitter(req);
        session.bindEmitter(res);

        session.run(function() {
            session.set('req', req);
            next();
        });
    });

and when you need it later on:

    var session = cls.getNamespace('mynamespace');
    var req = session.get('req');

Upvotes: 1

jfriend00
jfriend00

Reputation: 707148

Is there another way besides passing in the req variable as a parameter all across the framework?

No, not really. A node.js server (that uses any asynchronous operations) can have multiple requests in flight at the same time. So, any request-specific data that you want to access has to come from an object that is associated with this particular request and only this specific request. You can't put it in globals because those can be intermixed from different requests. You have several options, but ultimately you have to pass the data through your functions to wherever it is needed -there is no shortcut here. Here are several options:

  1. Put the data on req and pass req through your code to the function that needs the data.
  2. Pass the data itself (no need to pass the whole req object if you only need once piece of data.
  3. Create a new object that is specific to this particular request (not shared with other requests or available to other requests) and put the desired data as a property on that object and then pass that object through to the desired code. In an OO world, you can usually put multiple functions as methods on a shared object and then the data is automatically available to all those methods so you don't have to explicitly pass it.
  4. Use a shared scope and closure so that any functions that need access to the data can get it directly from a parent scope.

Upvotes: 1

Related Questions