Express 4 fire event on session ended

1.3k views Asked by At

I am setting a max age on the session cookie for an express session

app.use(session({ secret: process.env.EXPRESS_SECRET, key: 'sid', cookie: {secure: false, maxAge: 3000} }));

How can I use the event emitter, or custom events for express (which comes with an event emitter internally) - to fire an event when the session is ended and send data to the view layer?

1

There are 1 answers

2
alex On

Not sure I get what you want to achieve, but if you want to check the session has ended, you could just set a session data

if (req.session.isInit !== true) {
    // The session has been reinitialized
    // do something here
    req.session.isInit = true;
}

Otherwise, you could easily implement your own session store which would inherit the store of your choice (by default the express memory store which also inherits EventEmitter) and override the method #destroy which resets the session:

var MemoryStore = session.MemoryStore;
var inherits = require('util').inherits;

var MyStore = function () {
    MemoryStore.call(this);
};
inherits(MyStore, MemoryStore);

MyStore.prototype.destroy = function (sid, fn) {
    this.emit('resetSession');
    MemoryStore.prototype.destroy.call(this, sid, fn);
};

var myStore = new MyStore();
myStore.on('resetSession', function () {
     // do something here
});
app.use(session({ store: new MyStore()secret: process.env.EXPRESS_SECRET, key: 'sid', cookie: {secure: false, maxAge: 3000} }));