Search code examples
node.jsexpresscookiesexpress-session

Express session cookie not getting sent to the front end if I am setting secure=true in expression session


I am trying to set a cookie to store session using express-session. I am sending requests over HTTPS.

app.use(session({
    secret: env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: true, // Ensure secure is set to true for HTTPS
        sameSite: 'none', // Required for cross-origin cookies
        httpOnly: true,
        maxAge: 60 * 60 * 1000 // 1 hour         
    },
    rolling: true,
    store: MongoStore.create({
        mongoUrl: env.MONGODB_CONNECTION_STRING
    })
}));

If I only put:

cookie: {
        httpOnly: true,
        maxAge: 60 * 60 * 1000 // 1 hour         
    },

Then the cookie is received at the browser but it is not working because it is coming from https and cross origin. If I put:

cookie: {
        secure: true, // Ensure secure is set to true for HTTPS
        sameSite: 'none', // Required for cross-origin cookies
        httpOnly: true,
        maxAge: 60 * 60 * 1000 // 1 hour         
    },

Then the cookie is not received at the front end at all. I have deployed frontend and backend both at Vercel.

I tried to put secure: true, sameSite: 'none', in the cookie but then the cookie is not received at the frontend at all.


Solution

  • The issue has been resolved by setting proxy trusted.

    app.set('trust proxy', 1) // trust first proxy
    

    Mohit Sharma has confirmed the same in his comments.

    Citation:

    1. Express JS/ Node JS : Browsers are not setting cookie when secure=true, sameSite: 'none'

    2. express-session