When a successful login occurs from the backend, I’m trying to set a cookie, but it’s coming up as ‘undefined’ on Netlify, while everything works fine on localhost. When I check the Cookies from the application tab in the browser’s inspect tool, the cookie is visible, but when I try to retrieve it using Cookies.get() from js-cookie, it returns ‘undefined’. CORS origin is set to the site’s link in the backend with ‘credential true’.
Netlify live link: https://workmanager-srijonashraf.netlify.app/
//Backend Controller
exports.UserLogin = async (req, res) => {
try {
let reqBody = req.body;
let result = await EmployeeModel.find(reqBody).count();
if (result === 1) {
// Create JWT Token
const token = CreateJWTToken(reqBody);
res.cookie("token", token, {
httpOnly: process.env.NODE_ENV === "production",
secure: true,
sameSite: "None",
maxAge: 24 * 60 * 60 * 1000,
});
res
.status(200)
.json({ status: "success", email: reqBody["email"], token: token });
} else {
res.status(200).json({ status: "fail", data: "No User Found" });
}
} catch (e) {
res.status(200).json({ status: "error", data: e });
}
};
//CORS
app.use(
cors({
origin: [
"http://localhost:5173",
"https://workmanager-srijonashraf.netlify.app",
"https://work-manager-frontend.vercel.app",
"https://work-manager-frontend.vercel.app/:1",
/.netlify.app$/,
/.vercel.app$/,
],
credentials: true,
})
);
//Axios Call From Frontend
function UserLogin(email, password) {
const URL = `${BASE_URL}/UserLogin`;
const postBody = { email, password };
return axios
.post(URL, postBody, { withCredentials: true })
.then((res) => {
if (res.data.status === "success") {
setUserEmail(email);
console.log("All Cookies", Cookies.get());
console.log("Token from cookies:", Cookies.get('token'));
return true;
} else {
console.log("Login Failed");
return false;
}
})
.catch((err) => {
console.error(err);
return false;
});
}
Cookies.get() response from console of deployed site
I have tried:
- Changing the CORS policies
- Set the origin to wildcard (*)
- Deployed with and without credential : true properties in CORS
Srijon Ashraf is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.