Search code examples
node.jsexpresscookiesexpress-session

How can I set presistent cookies on node.js with express-session?


I want to create preistent cookies so that the user of my app doesn't have to login every time he enters the web. But instead, just require log in if he/she ever logs out. Basically, I would like to know if there is a way to set maxAge to infinity(equivalent) and the cookies to persist even if the user closes the browser. Here is my code:

app.use(expressSession({
  secret: '',
  resave: false,
  saveUninitialized: false,
  cookie: {
     secure: false,
     expires: false,
 }
}))

Solution

  • Based on the standards, you cannot set it to infinity:

    Max-Age=value OPTIONAL. The value of the Max-Age attribute is delta-seconds, the lifetime of the cookie in seconds, a decimal non-negative integer. To handle cached cookies correctly, a client SHOULD calculate the age of the cookie according to the age calculation rules in the HTTP/1.1 specification [RFC2616]. When the age is greater than delta-seconds seconds, the client SHOULD discard the cookie. A value of zero means the cookie SHOULD be discarded immediately.

    http://www.faqs.org/rfcs/rfc2965.html

    But as an alternative you can safely set the age to 5 years or 10 years later. Most probably a user would get rid of his device/PC/Mobile by this time. :)

    Update:
    To set the expiry time in future you can use MaxAge as following, setting it to expiry in a month:

    app.use(expressSession({
      secret: '',
      resave: false,
      saveUninitialized: false,
      rolling: true,
      cookie: {
         secure: false,
         maxAge: 30 * 24 * 60 * 60 * 1000
     }
    }))
    

    This would set it to expiry