Search code examples
javascriptnode.jsexpressexpress-session

Is it possible to get an express session by sessionID?


I have a NodeJS Express app that uses express-session. This works great, as long as session cookies are supported.

Unfortunately it also needs to work with a PhoneGap app that does not support cookies of any kind.

I am wondering: Is it possible to get an express session and access the data in that session, using the sessionID?

I am thinking I could append the sessionID as a querystring parameter for every request sent by the PhoneGap app like so:

https://endpoint.com/dostuff?sessionID=whatever

But I don't know how to tell express to retrieve the session.


Solution

  • You can certainly create an express route/middleware that tricks express-session that the incoming request contains the session cookie. Place something like this before the session middleware:

    app.use(function getSessionViaQuerystring(req, res, next) {
      var sessionId = req.query.sessionId;
      if (!sessionId) return res.send(401); // Or whatever
    
      // Trick the session middleware that you have the cookie;
      // Make sure you configure the cookie name, and set 'secure' to false
      // in https://github.com/expressjs/session#cookie-options
      req.cookies['connect.sid'] = req.query.sessionId;
      next();
    });