5

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.

user1031947
  • 5,172
  • 14
  • 48
  • 76
  • I don't think express-session supports anything but cookies, as it's generally assumed that everyone uses cookies these days anyway. You never really see anyone using querystrings for persistence anymore, that was in the nineties. – adeneo Apr 03 '15 at 01:42

2 Answers2

3

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();
});
lxe
  • 6,013
  • 2
  • 15
  • 30
2

Seems like req.cookies isn't accessible in my case. Here's another solution that recreates the session using the 'x-connect.sid' header (you may use any name or even a query param if you like).

Put this middleware after the session middleware

// FIRST you set up your default session like: app.use(session(options));

// THEN you recreate it using your/custom session ID
app.use(function(req, res, next){
    var sessionId = req.header('x-connect.sid');

    function makeNew(next){
        if (req.sessionStore){
            req.sessionStore.get(sessionId, function(err, session){
                if (err){
                    console.error("error while restoring a session by id", err);
                }
                if (session){
                    req.sessionStore.createSession(req, session);
                }
                next();
            });
        } else {
            console.error("req.sessionStore isn't available");
          next();
        }
    }

    if (sessionId) {
        if (req.session){
            req.session.destroy(function(err){
                if (err) {
                    console.error('error while destroying initial session', err);
                }
                makeNew(next);
            });
        } else {
            makeNew(next);
        }
    } else {
        next();
    }
});
Roman86
  • 1,601
  • 15
  • 18