How can I do something right before the session expire(destroy)

Hi I am using expressjs for my web application, and I use the session middleware, my question is that how I can do something right before the session expire?

For example, I store something in the session, and I set the req.session.cookie.maxAge to 60000(1 minute), when the session timeout, I want to save the data in the session to disk, how I can do this? I checked the API and the destroy function only support callback...

Thanks!

Assuming you're using connect-session there's nothing like session expiration event.

Sessions expire either :

  • on the client (when cookie gets outdated). There's no way to know about it until a request is made so there's a danger that the event will never get triggered.
  • in the session store, usually using some form of time-to-live. Not all session stores support events, so notification can't be done in general.

You can, however try implement your own check using setTimeout() - when it times out check if the session's expiration date is sufficiently close to now and do whatever you need to do.