Node.js run a function when an Express & Passport session expires

I have the maximum setting for session time using the following code (with Express.js and Passport.js).

  app.use(express.session({
    cookie: {
      maxAge : 3600000
    }
  }));

I would like to run the function if the session expires (for my log file and analytics). Something like that:

app.use(express.session.onExpiry(function(user){
        console.log('User session for ' + user + ' has expired.')
    });
);
+4
source share
1 answer

What you do is the cookie parameter "expires". The browser will clear the cookie as soon as it expires and you won’t know about it - it simply won’t come with one of the future requests.

, , , cookie, - cookie ( "expires" ) - (, 2037 ). , , cookie .

,

app.use(function(req, res, next) {
    //Checking previously set cookie (if there is one)
    var session = JSON.parse(req.cookies['session'] || '');
    if (session && new Date(session.expires) < new Date()) {
        console.log('User session has expired.')
    }

    //Resetting the cookie
    res.cookie('session', JSON.stringify({ session: <sessionIDKeyHere>, expires: Date.now() + 3600000 }), {
        expires: new Date(2037, 0, 1),
        httpOnly: true,
        secure: true //Do you have https? If no, set to false
    });

    next();
});
+1

Source: https://habr.com/ru/post/1535457/


All Articles