Search code examples
node.jsexpresscookiessession-cookiesthird-party-cookies

Session cookie not being set in browser


In my express application, I am using session middleware as follows

app.use(
    "/user",
    session({
        secret: sessionSecret,
        resave: true,
        saveUninitialized: true,
    })
);

I am setting authentication token in the session after successful login

user_route.post("/login", async (req, res) => {
    //Login logic

    req.session.authorization = {
        accessToken
    };

    console.log("In login route");
    console.log(req.session);
    return res
        .status(200)
        .json({ message: "User successfully logged in", accessToken: accessToken });
});

When I log session as above, the result contains authentication token. However, after login when I check in browser cookies, I can't find it.

In the subsequent requests, req.session.authentication is undefined.

I am currently handling it using another cookie but still session cookie should be set. Am I missing something here?


Solution

  • If frontend and backend are on different top-level domains (say, my.frontend.com vs. your.backend.com), the cookie counts as a third-party cookie and may be blocked based on your browser settings.

    The solution is to make the cookie partitioned by setting the partitioned option that was newly introduced into express-session:

    session({
      secret: sessionSecret,
      resave: ...,
      saveUninitialized: ...,
      cookie: {
        sameSite: "None",
        secure: true,
        partitioned: true
      }
    });
    

    Note that partitioned: true works only together with sameSite: "None" which in turn requires secure: true so that you must use HTTPS at least in the production environment, see I get the cookie from backend, but it is not set in frontend why?