I’m working on a React application hosted at http://localhost:5173 alongside a PHP backend that’s deployed to a live server. The authentication process utilizes JWT tokens, which are stored in HttpOnly cookies.
Upon successful login, the backend sets the cookie correctly and I can see it in my browser’s developer tools under Application → Cookies. However, the issue arises when I refresh the page; the cookie disappears entirely and the user is logged out again.
Here’s the PHP code I use to create the authentication cookie:
setcookie('jwt_token', $token, [
'expires' => time() + 3600 * 24,
'httponly' => true,
'samesite' => 'Lax',
'secure' => false,
]);
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: http://localhost:5173');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('X-XSS-Protection: 1; mode=block');
header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
What could be causing the HttpOnly cookie to be deleted after refreshing the page in this development environment? How can I ensure that the JWT cookie stays intact when my frontend is on localhost while the backend runs on a remote server?