phpreactjsauthenticationjwtsetcookie

JWT Cookie Removed After Page Refresh in React App (Frontend Localhost, Backend Server)


I'm developing a React app (http://localhost:5173) and a PHP backend hosted on a live server. I'm using JWT stored in an HttpOnly cookie for authentication.

When I log in, the backend sets the cookie successfully, and I can see it in Chrome DevTools → Application → Cookies. However, after I refresh the page, the cookie disappears completely, so the user gets logged out.

setcookie('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');

Why does the cookie get deleted on refresh in development? How can I persist the HttpOnly JWT cookie across page reloads when the frontend is local (localhost:5173) and the backend is hosted in the server?


Solution

  • Cookies might be dropped because of browser treat this as a cross-site interaction. Specially when using HttpOnly cookies to authentication between local frontend and remote backend.

    If the cookies domain mismatch the requesting origin(localhost) it will not be stored across the page reloads.

    serve frontend from the same server or use a proxy to eliminate cross-origin requests

    export default {
      server: {
        proxy: {
          '/api': {
            target: 'https://your-backend-domain.com',
            changeOrigin: true,
            secure: false,
          },
        },
      },
    };