Observing session create-destroy events in nodejs

I am using "express-session" and "memorystore". I want to log session create and destroy activities. My solution is, taking a snapshot of the current "sessionStorage" and a while later, compare it with the current "sessionStorage" and based on the differance, report session created, destroyed activites.

let sessionSnapshot;
app.get('/',
function (req, res, next) {
    let currentSnapshot = req.sessionStore;
    let difference = sessionSnapshot.filter(x => !currentSnapshot.includes(x));
    // Report create/destroy activities based on difference.
});

Is there any other places / callbacks that I can track session create and destroy events ?
I am using "passport" as well.

4 thoughts on “Observing session create-destroy events in nodejs”

  1. You can monkey patch this function https://github.com/expressjs/session/blob/master/session/memory.js#L93-L96

    const MemoryStore = require('./node_modules/express-session/session/memory.js');
    
    const originalSet = MemoryStore.prototype.set;
    MemoryStore.prototype.set = function set(sessionId, session, callback) {
      console.log('saving session with id %s and parameters', sessionId, session);
      return originalSet.call(this, sessionId, session, callback);
    }
    
    // for destroy
    const original = MemoryStore.prototype.destroy;
    // patched function
    MemoryStore.prototype.destroy = function(sessionId, callback) {
      console.log('destroying session with id %s', sessionId);
      return original.call(this, sessionId, callback)
    }
    
    

    and then, you can use this patched memory store in application

    app.use(session({
        cookie: { maxAge: 86400000 },
        store: new MemoryStore({
          checkPeriod: 86400000 // prune expired entries every 24h
        }),
        resave: false,
        secret: 'keyboard cat'
    }))
    
    Reply

Leave a Comment