I recently discovered that using credentials: "include" successfully prevents the cookie from being accessed by JavaScript, and it works as expected. However, I encountered an issue where, upon JWT session expiration, the backend returns a 401 Unauthorized error. While a 401 error is commonly used for authentication issues, it may not be the most ideal way to handle token expiration. This is because a 401 error could also result from role-based access restrictions, which would make redirecting to the /login page inappropriate in such cases. Therefore, a more refined approach is needed to distinguish between these scenarios and handle them accordingly.
I'm using React as Frontend and Spring as Backend
Below is one such request:
const handleLoginRequest = async (e) => {
try {
const response = await fetch('http://localhost:3000/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-XSRF-TOKEN': csrfToken || "",
},
body: JSON.stringify(formData),
credentials: 'include'
});
console.log(response)
const data=await response.json()
console.log(data)
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || 'Login failed');
}
console.log('Login successful!');
} catch (err) {
setError(err.message);
}
};