Reputation: 697
I am in a weird situation where cookie is not getting set in browser and in response its showing in browser
Response Screenshot from Network Tab
React Application Running on Domain - https://2367cc15b.eu.ngrok.io
Node Js Running On Domain - https://e17b14c2835b.ngrok.io
Code to set cookie
res.cookie('holofyKey', holofyKey, { httpOnly: true, domain: '.ngrok.io', expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) });
I am using app.use(cookieParser());
in my middleware.
Is there something i am missing ?
PS - I tried with removing httpOnly and domain name from options still no luck
Upvotes: 1
Views: 2897
Reputation: 697
After 2 days trying every possible solution this finally worked for me
This is how you need to call the api from which you want to set the cookie.
const postHelper = async (url, body) => {
return await fetch(url, {
method: "POST",
headers: {
Accept: "applicaiton/json",
"Content-Type": "application/json",
},
body: body && JSON.stringify(body),
withCredentials: true, // should be there
credentials: 'include' // should be there
});
};
After adding this you will get CORS error so please add this line of code in your server
app.use(cors({ origin: true, credentials: true }));
And finally
res.cookie('cookieKey', cookieKey, { expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)), secure: true });
PS - This solution will work in case of Cross domain and same domain but in case of cross domain most browsers will not allow you to set cookie until user agree.
Upvotes: 4