Search code examples
koakoa-session

koa session expire event


Am trying to log a message when a koa session expires. But adding a listener for the expire event doesnt seem to work for me.

Following is the sample code. Set 2 mins as maxAge for the session.

import koa from 'koa';
import serve from 'koa-static';
import route from 'koa-route';
import session from 'koa-session';
import mount from 'koa-mount';

let pub = new koa();
let parse = new koa();
let app = new koa();

app.keys = ['test'];

const CONFIG = {
    key: 'sess',
    maxAge: 2000
};

parse.use(ctx => {
    // ignore favicon
    if (ctx.path === '/test') return;

    let n = ctx.session.views || 0;
    ctx.session.views = ++n;
    ctx.body = n + ' views';
    console.log(ctx.session);
});

pub.use(serve('./public'));

app.use(session(CONFIG,app));
app.on('expired',(key,value,ctx) => console.log(key));

app.use(mount('/',pub));
app.use(mount('/parse',parse));


app.listen(8080);

Here everytime i refresh the page after 2 seconds in browser i can see the "views" value set back to 1 meaning the previous session had expired. But the log statement as part of the expired event is not getting hit. May be the way am adding the event listener is wrong. Can someone please help?


Solution

  • After having a look at library files, koajs/session -> context.js

    if (value._expire && value._expire < Date.now()) {
      debug('expired session');
      this.emit('expired', { key, value, ctx });
      return false;
    }
    

    where emit is:

    emit(event, data) {
        setImmediate(() => {
          this.app.emit(`session:${event}`, data);
        });
    }
    

    So I think in your code you shouldchange the name you are trying to capture the event with:

    app.on('session:expired',(key,value,ctx) => console.log(key));
    

    If key is containing a value, you should see something printing out in the console :)