Ask Question

How to extend session with express-session?

I am using express together with express-session in order to handle user session after the've logged into my application. The problem is that they will be logged out again after some time or when they close the browser window. What would be a good solution to achieve a long living user session?

This is my current express-session config:

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: true }
}));
nodejsExpress

4715 views

AuthorΒ΄s Dominik Sumer image

Dominik Sumer

Last edited on

2 Answers

Best answer

In your express-session no expiration date or maxAge is configured, so the cookie will be bound to the "browser session" by default.

A good solution would be to set the maxAge of the cookie to a desired time and also specify the rolling configuration of express-session, which renews the maxAge if a user is active (a request is being sent) on your application.

Example config:

app.use(session({
  ...
  cookie: { 
    ...
    maxAge: 7 * 24 * 3600 * 1000, // a week
  },
  rolling: true
}));

So with the config above the cookie will be valid for a week, but if the user is for example again visiting your application after 3 days, the cookie will then be renewed for again 7 days.

Link to documentation of the rolling config: https://github.com/expressjs/session#rolling

πŸ‘
1

I dont want to set rolling to be true , on changing maxage of session cookie , changes are made to the db but in the response of api res-cookie is not sent due to whixh browser session cookie is not refereshed.Can you tell me how could this occur?