Search code examples
node.jsexpresssessioncookiesweb-development-server

Not able to set an expiration date to a session cookie using express


I was trying to create a session for a client, and tried to set an expiration date for the cookie to expire after a day by -

const session = require('express-session')
const sessionConfig = {
    secret: 'thiswillbeupdatedinthefuture',
    resave: false,
    saveUninitialized: true,
    cookies: {
        expires: Date.now() + 1000*60*60*24,
        maxAge: 1000*60*60*24,
        httpOnly: true
    }
}
app.use(session(sessionConfig))

I got no error executing the code, but when I inspected the web-page and saw the cookie details under the Application section, it still showed the Expires/Max-Age column for the connect.sid cookie to be set to Session instead of the expiration date I expected. I also tried to print the cookie in console using - console.log(req.session) and the output was -

Session {
  cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }
}

which probably means that the expiration date has still not be changed to what I expected. Please help me understand why this problem is occurring and find a possible solution for it.


Solution

  • Expires attribute expects Date as an argument, so you should use: new Date(Date.now() + 1000*60*60*24).

    Additionally, you should not mix Max-Age and Expires.

    From MDN Web Docs:

    If both Expires and Max-Age are set, Max-Age has precedence.

    So use either Max-Age or Expires.

    And I just noticed that you are using cookies keyword, but in the express-session docs I see cookie everywhere. So it looks like typo in your code.