node.jsexpresscookie-session

Resetting cookie-session expiry time


I am trying to set the expiry time of cookie-session dynamically based on the value pulled from the database. For some users the value might be less or more than other user.

When the server initializes this is how I am setting up my cookie-session:

server.use(require('cookie-session')({
  name: 'session',
  secret: keys.session.secret,
  maxAge: 1 * 10 * 60 * 1000,
}));

I wanted to reset the cookie based on inactivity so this code resets the expiry date to maxAge value based on activity.

server.use(async (req, res, next) => {
  try {
    // Reset inactivity
    // Update a value in the cookie so that the set-cookie will be sent.
    // Only changes every minute so that it's not sent with every request.
    req.session.nowInMinutes = Math.floor(Date.now() / 60e3); // 
     ....

So based on some research online, I saw that I should be able to reset the value of the expiry doing something like this:

// 30 seconds is just a test. I will pull the expiry value from the database based // on 
// user ID but for now if a login is detected change the expiry date to 30 seconds
// 
 if (req.user) {
  // Reset max age of cookie to 30 seconds
  res.cookie('cookieName', 'value', { maxAge: 30 * 1000 });
}

This does not seem to work. The session value in browser still shows 10 minutes after current time:

enter image description here

How would I dynamically set the expiry value for a a user cookie ideally only once.


Solution

  • You can change the maxAge option for specific request via req.sessionOptions

    Represents the session options for the current request. These options are a shallow clone of what was provided at middleware construction and can be altered to change cookie setting behavior on a per-request basis.

    E.g.

    const cookieSession = require('cookie-session');
    const express = require('express');
    const fs = require('fs');
    const path = require('path');
    
    const app = express();
    
    app.use(
      cookieSession({
        name: 'session',
        secret: 'test',
        maxAge: 1 * 10 * 60 * 1000,
      }),
    );
    
    app.use(function (req, res, next) {
      req.session.nowInMinutes = Math.floor(Date.now() / 60e3);
      next();
    });
    
    app.get('/', function (req, res) {
      fs.createReadStream(path.resolve(__dirname, 'index.html')).pipe(res);
    });
    app.get('/user/:id', function (req, res) {
      req.sessionOptions.maxAge = 30 * 1000;
      res.sendStatus(200);
    });
    
    app.listen(3000, () => console.log('listening on port 3000'));
    

    Access http://localhost:3000 first, then http://localhost:3000/user/1 to check the changes of Expires / Max-Age