Cookie gets removed on refreshing or reload: I am using express js to set cookie and react as a frontend:
Can anyone explain why coocki gets deleted after refreshing page?....please help as soon as possible
i am sharing files to inspect for your reference:
Deployed site for your reference: https://shoppynexxa.vercel.app/
jwtToken.js -- backend
const sendToken = (user, statusCode, res) => {
const token = user.getJWTToken();
const options = {
expires: new Date(Date.now() + process.env.COOKIE_EXPIRE * 24 * 60 * 60 * 1000),
httpOnly: true,
secure: true,
domain: "shoppynexxa-backend.onrender.com",
}
res.cookie("token", token, options);
res.status(statusCode).json({
success: true,
user,
token,
});
}
module.exports = sendToken;
login controller from where sendToken is being called after verifying user: -- backend
//Login User
exports.loginUser = tryCatchWrapper(async (req, res, next) => {
const { email, password } = req.body;
//checking weather email and password entered by user or not
if (!email || !password) {
return (next(new ErrorHandler("Please Enter Email And Password", 400)))
}
const user = await User.findOne({ email }).select("+password");
//checking weather user is exist or not
if (!user) {
return (next(new ErrorHandler("Invalid Email or Password", 401)));
}
//compare password entered by user and db password
const isPasswordMatched = await user.comparePassword(password);
if (!isPasswordMatched) {
return (next(new ErrorHandler("Invalid Email Or Password", 401)))
}
if(user.emailVerified) {
sendToken(user, 200, res);
} else {
await sendVerificationEmail(user, res);
return;
}
});
api.js for centralizing api calls -- frontend
// src/api.js
import axios from 'axios';
const api = axios.create({
baseURL: 'https://shoppynexxa-backend.onrender.com', // Set your base URL
withCredentials: true,
headers: {
'Content-Type': 'application/json', // Example header
}
});
export default api;
useraction.js from where api call for login made: -- frontend
//Login
export const login = (email, password) => async (dispatch) => {
try {
dispatch({ type: LOGIN_REQUEST });
const config = { headers: { "Content-Type": "application/json" }, withCredentials: true}
const { data } = await api.post(
`/api/v1/login`,
{ email, password },
config,
);
if (data.mailSent) {
dispatch({ type: LOGIN_FAIL, emailVerification: !data.mailSent })
} else {
dispatch({
type: LOGIN_SUCCESS,
payload: data.user,
})
}
} catch (error) {
// console.log("error", error);
dispatch({ type: LOGIN_FAIL, payload: error.response.data.message })
}
}
suggestions how can i tackle this.
Set-Cookie
header that your API sets.