Not able to receive/set cookies in browser from backend in MERN app with backend hosted on heroku and frontend on netlify Not able to receive/set cookies in browser from backend in MERN app with backend hosted on heroku and frontend on netlify heroku heroku

Not able to receive/set cookies in browser from backend in MERN app with backend hosted on heroku and frontend on netlify


You are correct. Cookies are not cross-domain compatible. If it was, it would be a serious security issue. The easiest way to fix your problem would be to send back the cookie as a res object, and then setting the cookie manually in the frontend.

Take this for example. I'll do this with JavaScript style pseudocode. Don't copy paste this as this most likely wouldn't work right away. This is what you're going to do on the back-end:

// 1. Authenticate the user.const userData = await authenticateUser();const userToken = await verifyUser(userData);// 2. Return the response object.return response.status(200).json({  status: 'success',  data: userData,  token: userToken,});

In the front-end:

const response = await axios.post(...); // your API call, will return above object.// set your authentication token here.// the 'options' object will contain all possible cookie options, example would be 'secure'.cookies.set('token', response.data.token, options);// alternatively, set the cookie in the local storage.localStorage.setItem('token', response.data.token);

You need to set the cookie accordingly in the front-end.

Further reading: MDN Docs


EDIT: Your question is unclear. First time you talked about cookies, but now you're talking about httpOnly cookies. Please be more specific in your questions.

It is impossible to set httpOnly cookies in React.js if it is cross-domain. React is only responsible for the 'view' of the website. httpOnly cookies are only meant to be set server-side. Client-side JavaScript cannot read or set that specific cookie, but it is able to send it. Unless you have something in your Netlify that can do server-side operations, I don't think that is possible.

Your best bet is to actually just use the same domain.