ksloan
ksloan

Reputation: 1492

How to hook into express session creation event

How can I tell when express creates a new session? I'm using a mongodb session store.

I'm having an issue with extra sessions being created, and want to narrow down on the problem by tracking which urls requests are triggering new sessions to be created.

Upvotes: 2

Views: 1182

Answers (3)

Christiaan Westerbeek
Christiaan Westerbeek

Reputation: 11157

The answer by Nate is fine. I'm answering because of 2 additions I'd like to make.

  1. In case you also want the kind of sessionID that express-session would otherwise generate. You can do this:
const uid = require('uid-safe').sync;
//...

    genid: function(req) {
        console.log('New session was created');
        // do what you want to do here!
        return uid(24); // <-- the way express-session generates it
    },
  1. Be aware that you cannot use an async function for genid. Express-session calls this function without await, so that would get a promise instead of the uid.

Upvotes: 1

ksloan
ksloan

Reputation: 1492

This is what I ended up doing.

app.use(function(req, res, next) {
    if (!req.session.returning) {
        // session was just created
        req.session.returning = true
    } else {
        // old session
    }
    next()
})

Upvotes: 3

Nate
Nate

Reputation: 19030

You can hook into the genid callback. By default express-session generates its own session IDs.

But you can generate the session ID yourself by specifying a genid callback. Within this callback you can log that a new session is being created (and then return a unique session ID).

Here is an example, adapted from the express-session README:

app.use(session({
  genid: function(req) {
    console.log('New session was created');
    return genuuid(); // generate a UUID somehow and return it
  },
  secret: 'keyboard cat'
}));

Upvotes: 2

Related Questions