Node.js session and Timeout

Photo by: Miguel Á. Padriñán

When using express-session, it is pretty easy to let your cookie expired after a certain time period, simply set a maxAge or an expires.

Basic usage

Note that maxAge takes an integer and expires takes a date object. Full doc at here.

// maxAge of 30 minutes
app.use(
  session({
    secret: 'mySecret',
    cookie: { maxAge: 30 * 60 * 1000 },
  })
);

// or

// expires in 30 minutes from now
app.use(
  session({
    secret: 'mySecret',
    cookie: { expires: new Date(Date.now() + 30 * 60 * 1000) },
  })
);

Go further

What if I need to make other variables which is not stored in session expires together with the session?

In the following scenario, I need a global variable removed together with some data stored in my express session. So here I went with setTimeout as a solution, if any better idea pops up, I will update this post.

var setPending = function() { // some code to initialize pending number };


var removePending = function() { // some code to remove pending number };

// check after 30 min, if session is expired, remove pending number
if (setPending()) {
  var timeout = setTimeout(function() {
    if (req.session.cookie._expires < new Date()) {
      return removePending();
    }
  }, 30 * 60 * 1000);
}

  TOC