Search code examples
javascriptnode.jsexpressexpress-session

Express session - Session lost after opening a link on another tab


Background:

I have a nodejs app using express-session for session management. Recently we had a security checkup for the app and started using secure cookies. Here is the express-session configurations:

server.use(
    session({
        saveUninitialized: true,
        rolling: true,
        resave: true,
        proxy: true,
        secret: envConfig.sessionSecret,
        cookie: {
            maxAge: envConfig.sessionCookie.maxAge, 
            httpOnly: envConfig.sessionCookie.httpOnly, // was false before security checkup
            sameSite: true, // was false before security checkup
            secure: envConfig.sessionCookie.secure // was false before security checkup
        },
        name: envConfig.sessionKey,
        store: new MongoDBStore({
            uri: envConfig.sessMongoDB.uri,
            collection: envConfig.sessMongoDB.collection,
            expires: envConfig.sessMongoDB.expires,
            connectionOptions: {
                useNewUrlParser: true,
                useUnifiedTopology: true
            }
        })
    })
);

The problem:

The issue starts here. This session management works well and stable. But if we share any link through mail or whatsapp web or any messaging app and anyone clicks that link. They will loose there session and in another word the person signs out from the application.

Seems that the browser is not sharing current cookies with the newly opened tab and generates a new session.

Has anyone experienced this issue before and how can we overcome this issue?

UPDATE 1: Seems that the issue is with WhatsApp web. When we open the link through WhatsApp web we loose the session


Solution

  • I managed to solve this problem 1 day after I posted this question. I forgot to share. The issue was about the cookies SameSite policy.

    If you put strict value to SameSite. It will cause cookie loose if the you open the webpage from a link that is on another host.

    From MDN:

    Cookies will only be sent in a first-party context and not be sent along with requests initiated by third party websites.

    More information can be found here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite