Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node/Express with connect-redis, how handle session expiry

I have a Node/Express application that use redis as session store.

I have a question concerning the handling of the expiry of the session.

I'd like have an active session until the browser is closed, so I didn't set a session expiration time.

Doing that the session cookie works fine, but I have a doubt about Redis.

It seems that the couple Key/Value stored in Redis DB never expire.

How is the right way to handle this?

There is a way to configure redis to destroy a value stored with a certain idle time?

Or is better set a TTL when the connect-redis is invoked inside the application?


Actual configuration of the session inside the application:

var session = require('express-session');
var RedisStore = require('connect-redis')(session);

app.use(session({
  store: new RedisStore({port:6379, host: 'localhost'}),
  secret: "my-secret-here",
  resave: false,
  saveUninitialized: true }));
like image 233
Zauker Avatar asked Oct 21 '25 08:10

Zauker


2 Answers

Using Redis with express-session, you can use the touch() method from express-session to reset the TTL. So if you set a TTL when creating the session, do something like this on the routes where you don't want the session to expire:

api.get("/someRoute/", (req, res) => {
  req.session.touch();

  // Whatever else you need to do
  res.sendStatus(200);
}

That will reset the TTL on Redis and prevent the session from expiring assuming the client is still hitting your API - I'm assuming that if the client doesn't interact with your API for long enough, that implies the browser is closed or otherwise finished using your app.

like image 62
Levi Morris Avatar answered Oct 23 '25 22:10

Levi Morris


You can specify a ttl while creating the session store. You can find more options in the readme.

app.use(session({
    store: new RedisStore(options),
    secret: 'keyboard cat',
    ttl : 20 // ttl is in seconds. From the readme.
}));
like image 43
Swaraj Giri Avatar answered Oct 23 '25 23:10

Swaraj Giri