Backend is written with Expressjs:
middleware used as following
app.use(cookieParser())
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", process.env.FRONTEND);
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,OPTIONS");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, x-csrf-token");
next()
});
argument for sending cookie:
try {
const oneHourFromNow = new Date(Date.now() + 3600000)
const Admins = await Admin.find({ password: req.body.password, name: req.body.name }).select("-password").select("-token").select("-_id");
if (Admins.length > 0) {
res.cookie("admin-cookie", "123", {
httpOnly: false,
secure: true,
// sameSite: "none",
expires: oneHourFromNow,
domain: process.env.DOMAIN,
path: "/",
});
res.status(200).send("Cookie set")
Frontend request detail:
const handleSubmit = async (event) => {
console.log("state", username, password)
event.preventDefault();
let data = JSON.stringify({
"name": username,
"password": password
});
let config = {
method: 'post',
maxBodyLength: Infinity,
// url: 'http://localhost:5000/client/login',
url: `${process.env.REACT_APP_BASE_URL}/client/login`,
headers: {
'Content-Type': 'application/json',
},
data: data,
credential: 'include'
};
axios.defaults.withCredentials = true;
axios.request(config, { withCredentials: true })
.then((response) => {
console.log("cookie response", response)
if (response.status === 200) {
console.log("success")
// window.location.href = "/products";
}
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
};
After I hosted both as two separate Cloud Run service on GCP, the request can be sent with correct response status 200, and a cookie can be found under inpection(F12) -> network -> login as below:enter image description here
Note there's a exclamation mark around Domain, but I find no explanation for that...
However, under application, storage -> cookies, it's not there enter image description here
I tried everything I can find online and none worked.
A few things worth noting for troubleshooting:
- cookie is presents in the response, so the request is successfully made, and the response does receive a header with 'Set-cookie' and its cookie detail
- it also works fine in localhost and with postman, for localhost, I can see the cookie being stored under application -> storage -> cookies
- frontend and backend are hosted on different URL generated by GCP Cloud Run
I tried change the CORS policy header, I tried adding withCredential in multiple ways in the frontend and numerous console.log, I also tested with local deployment and postman. I pretty much tried what I can find online, none has worked.