I can’t store cookies from express server to react front-end when the app deployed online, but it works just fine in localhost. The server did response with a cookie but the client won’t save it, what is the problem? I’m using cookieParser midleware for the server
Client side request (React)
const handleLogin = async (e) => {
e.preventDefault();
try {
setLoading(true);
const url = '/login';
const response = await axios.post(
url,
{
email: email,
password: password,
},
{
withCredentials: true,
}
);
axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.payload}`;
setHidden(true);
navigate('/');
} catch (error) {
setLoading(false);
setHidden(false);
setErrorMsg(error.message);
}
};
Server request handler (Express)
export const Login = async (req, res) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email: email });
if (!user) {
return response(400, {}, 'Email or password does not match!', res);
}
const matchUser = await bcrypt.compare(password, user.password);
if (!matchUser) {
return response(400, {}, 'Email or password does not match!', res);
}
const ACCESS_TOKEN = accessToken(email);
const REFRESH_TOKEN = refreshToken(email);
const addToken = new RefreshToken({
token: REFRESH_TOKEN,
});
await addToken
.save()
.then(() => {
res.cookie('ref_token', REFRESH_TOKEN, {
sameSite: 'none',
secure: true,
maxAge: 7 * 24 * 60 * 60 * 1000,
});
response(201, ACCESS_TOKEN, 'Login success!', res);
})
.catch((error) => res.send(error));
} catch (error) {
console.log(error);
}
};
I have tried many things like changing cookie properties settings but still it won’t work, only work in localhost. It should be working as proper as it works offline.
2
Answers
Do you have a .env file that you did not configure on the deploy server?
If your cookies are working fine on localhost but not when deployed online, there are several potential reasons for this issue. Let’s explore some common causes and troubleshooting steps:
Domain Mismatch: When deploying your application online, the domain of your frontend and backend might not match. Cookies are subject to the same-origin policy, meaning they can only be set and read by the same domain. Ensure that your frontend and backend are hosted on the same domain or, if they are on different subdomains, set the cookie domain appropriately.
Secure Attribute: If your backend is served over HTTPS but your frontend is not, some browsers may not store the cookie due to security reasons. Cookies with the "Secure" attribute can only be set over secure connections (HTTPS). Make sure your frontend is also served over HTTPS.
Path Attribute: Check if you have specified the correct "path" attribute when setting the cookie. If the path is too restrictive, the cookie may not be accessible from your frontend’s current location. Setting the cookie path to ‘/’ should make it accessible throughout the entire domain.
HttpOnly Attribute: If you have set the cookie with the HttpOnly attribute on the server-side, it will not be accessible from client-side JavaScript. This attribute is used for added security to prevent cross-site scripting (XSS) attacks.
SameSite Attribute: Some browsers may not store cookies with a missing or invalid "SameSite" attribute. This attribute is used to control when the cookie should be sent to the server. Common values are "Lax" or "Strict". Make sure you set an appropriate value for your use case.
Third-Party Cookie Blocking: Some browsers may block third-party cookies by default. If your frontend and backend are hosted on different domains, consider using CORS (Cross-Origin Resource Sharing) to handle cross-origin requests.
Server Configuration: Check your server’s configuration to ensure it’s not explicitly preventing cookies from being set. For example, certain security middleware might interfere with cookie settings.
Client-Side Code: Double-check your React frontend code to ensure that you are not inadvertently overwriting or clearing the cookie.
To troubleshoot the issue effectively, you can use browser developer tools to inspect the network requests and see if the "Set-Cookie" header is being sent from the server and if the cookie is being saved. Additionally, check the console for any error messages related to the cookie.
If you provide more specific details about your backend (Express) and frontend (React) code and how you are setting the cookie, I can help you further in diagnosing the problem.