Use of withCredentials when calling backend API
on 10/06/2025
Hello,
When trying to call backend API to save/retrive a token to/from cookies and you already configured CORS. you will have to pass withCredentials within frontend header
const response = await axios.post<{ user: User; token: string }>(
`${BACKEND_URL}/api/auth/GetJwtCookie`,
{ email: "admin@panora.tech" },
{
headers: {
accept: "*/*",
"Content-Type": "application/json",
},
maxBodyLength: Infinity,
withCredentials: true,
},
);
Assume the backend will try to generate a JWT token and store it in cookies like below:
var token = _jwtTokenService.GenerateToken(userInStore.Id, loginRequest.Email, string.Empty);
Response.Cookies.Append("JwtSettings", token, new CookieOptions
{
HttpOnly = true, // Prevents JavaScript access (secure)
Secure = true, // Required for HTTPS (set to false for localhost)
SameSite = SameSiteMode.None, // Required for cross-origin cookies
Expires = DateTime.UtcNow.AddDays(7) // 🔥 Persist cookie for 7 days
});
By using withCredentials will tell backend to safely and securely (authorization/authencation) save the token to cookies.