in my express i use res.cookie to post a cookie
res.cookie("jwt", token, {
expires: new Date(Date.now() process.env.COOKIEEX * 24 * 60 * 60 * 1000),
withCredentials: true,
httpOnly: false,
});
res.status(200).json({
status: "success",
user,
token,
});
but when i send a req to that middleware from my react app using axios i find the cookie in the network > headers> set-cookie , but its not sets in the browser:
<form
onSubmit={async (e) => {
e.preventDefault();
const res = await axios.post(
"http://127.0.0.1:3000/api/v1/users/login",
{
email: "[email protected]",
password: "password@",
},
{ credentials: true }
);
}}
>
i also tried to set samesit=None and secure, its works and i can see the cookie in the browser but after refreshing the page it disappears :
res.cookie("jwt", token, {
expires: new Date(Date.now() process.env.COOKIEEX * 24 * 60 * 60 * 1000),
withCredentials: true,
httpOnly: false,
sameSite:"None",
secure:true
});
CodePudding user response:
Browsers are less and less likely to include cookies over HTTP, instead you should try to only use HTTPS when a browser is involved.
Samesite=none;secure only works over HTTPS and will not be included in requests over HTTP. When you don't include any samesite, the default is then set to Lax (I think) and that means that it will not be included in POST requests to a different site. To do cross-site requests with cookies, you need to set samesite=none;secure and use HTTPS.
CodePudding user response:
As far as I know, when you work with cookies, the backend (express in your case) handle the settings of the cookies in your browser [SESSION], in an another word, you just need to set { credentials: true }
in your frontend app, the token that was saved on your browser is logically saved in your DB, so whenever a request coming, there is a check on the DB if the two tokens matches [ the one coming from the req
and the one is saved on your DB ].
So mainly, or again as I know it's not gettable in other word if you just need something which is included in your token, just send it explicitly.