Cross domain cookies with fetch in React and NodeJS/Express

Viewed 19

I have a React app running on one domain and an API in NodeJS with Express on a different domain. In one of the API routes I set Response cookies, send response, once received on the Frontend, another route is called which gets the cookies from Request to use them. On local, with front end served on localhost:3000 and API on localhost:5000 it all works. But on production (or if I use ngrok to forward localhost:5000 to https://some-randome-number.ngrok.com) it doesn't. There are a lot of articles online around this topic, but for some reason nothing helps. Here is what I have:

In React

fetch(url, { credentials: 'include',  ...options }).then(...)

In API

    const options: CookieOptions = {
        expires: new Date(Date.now() + halfYear),
        sameSite: "none",
        secure: true,
        httpOnly: true,
        domain: "my-front-end.web.app" // I tried with and without this
    }
    res.cookie("cookie name", "cookie value", options)

When the second route is called, req.headers.cookie is undefined. I also check in the Dev Tools and there are no cookies that I expect to see there. However there are a whole bunch of google cookies, which makes me believe that what I need to achieve is in fact doable. I also have on the API side:

    app.use((req: Request, res: Response, next: NextFunction) => {
        res.setHeader("Access-Control-Allow-Credentials", "true");
    })

I would really appreciate some help on how to set it up or if it can't be done an explanation on why not.

0 Answers
Related