Express Session Different Expiration Express Session Different Expiration express express

Express Session Different Expiration


You can use cookies and set different expirations on different cookie names. So you can have multiple cookies that would hold data and each one would have a specific expiration.

That being said, I would say that both sessions and cookies wouldn't be the correct solution to your problem. I would keep your sessions lean and store the data in a database. Considering you're using sessions, you could use Redis and store data with expirations. You could assign the key in Redis to your session. For example:

req.session.myDataA = 'user_id:myDataA'req.session.myDataB = 'user_id:myDataB'

When you set your data in Redis, you can use the key user_id:myDataA and set it to expire.

// Will expire in 1 hourSET user_id:myDataA "your data"EXPIRE user_id:myDataA 3600

While the key will still be in session, you can check if the value is null or has the data you're expecting.

I know this perhaps sounds a little more complicated, but even as a good practice with sessions, you really don't want to be storing a lot of data, beyond keys of reference as it becomes very difficult to manage.

If you're using MongoDB, you could also set documents to expire. However, if you're not using either, Redis would generally be the easiest to setup and acts a good session store.

Edit:

As commented below, instead of expiring the sessions which you can't at different time frames, is to just set a field in your data with expiration time. Then when you get that data, check if it's passed expiration (i.e., 1hr, 30days, etc.).


You could set the maxAge of session in another middleware

code:

// after session and passport middlewareapp.use(function(req, res, next) {    if (req.session.user) { // some condition        req.session.cookie.maxAge = 1000 * 60 * 60 * 24 // 24 hours    } else if (req.session.myData) {        req.session.cookie.maxAge = 1000 * 60 * 60    }    // another condition    // save the session    req.session.save()    // add next at the end of middleware     // so it can pas data edited to another middleware    next()})