node.jsexpresscookiescookie-session

My cookies don't persist after i restart the browser


I am using cookieSession to deal with session matters. No problem except when i restart the browser, my session doesn't persist. I wish sessions remain active every time and never expire.

Here is my setup

app.use(cookieSession({
  name: 'xxxx',
  keys: ['xxxxx', 'xxxx'],
  cookie: { secure: true,
            httpOnly: true,
            domain: 'mydomain.com',

            expires: 9999999999999999999999999999999999999999 
          }
  })
); 

Any suggestion ?


Solution

  • Looking at the cookie-session readme, I don't think you need to nest your options in a cookie property. Also, expires takes a Date object; you should pass that value as maxAge instead if you wish to give it the number of milliseconds until the cookie expires. Keep in mind that all cookies expire per the cookie specification, so the best you can do is set an expiration time very far in the future.

    Try this:

    app.use(cookieSession({
      name: 'xxxx',
      keys: ['xxxxx', 'xxxx'],
      secure: true,
      httpOnly: true,
      domain: 'mydomain.com',
      maxAge: 9999999999999999999999999999999999999999 
      })
    ); 
    

    EDIT: Some older browsers don't support maxAge, so expires might be better for compatibility. Also, watch out for overflow in maxAge; a negative value may cause the browser to expire the cookie immediately or when the browser closes. Consider using Number.MAX_SAFE_INTEGER.