Express-session not deleting previous sessions

Viewed 1253

I am currently working on a new project and I use sessions with the express-session library.

Here is the code where I set up the session:

const IN_PROD = process.env.MODE==='production'
app.use(session({
    name: 'sid',
    secret: 'asecret',
    store: new MongoStore({
        mongooseConnection: mongoose.connection,
        collection: 'sessions'
    }),
    saveUninitialized: false,
    resave: false,
    cookie: {
        sameSite: true,
        secure: IN_PROD,
        expires: new Date(new Date().getTime() + 1000 * 60 * 60 * 24)
    }
}))

Imagine the following steps:

1) My server sends a session id (sid=A) in a cookie to my client.

2) The client manually deletes the cookie

3) At the next request, the client sends another session id (sid=B)

Is it normal that both A and B cookies are stored in the database and the first one is not overridden?

1 Answers

It is normal. It is up to either you or the session store you use to clean up older sessions.

If you look at the MongoStore() documentation, you will see that it has several features related to automatic removal of session objects.

Here's one example:

// connect-mongo will take care of removing expired sessions, using defined interval.

app.use(session({
    store: new MongoStore({
      url: 'mongodb://localhost/test-app',
      autoRemove: 'interval',
      autoRemoveInterval: 10 // In minutes
    })
}));

Keep in mind that at the express-session level, a session is just a blob of data associated with a cookie. Any time a browser makes a request to your server and no session cookie exists, a new session cookie is created and a new express-session object that is connected to that new cookie.

If the user then deletes that cookie and connects to your server again, express-session has no idea that this browser is the same browser as the previous session. The original cookie is the only way it could know that and the cookie is now gone. So, express-session just sees a new browser connecting to your server that doesn't have a session cookie so it creates a new cookie and then creates a new session object to go with it.

Any association of a logged in user with an express session is done at your application level (by putting user-identification information into the session object) and express-session is not aware of that at all.

Related