Your use-auth.tsx hook looks well-structured, but there are a few potential issues that could cause problems with session handling and JWT authentication. Here are some areas to check and debug: 🔍 Potential Issues and Fixes 1️⃣ LocalStorage Token Not Persisting or Fetching Correctly Issue: The localStorage token may not be set correctly or retrieved before API requests. Fix: Add a console.log(localStorage.getItem("auth_token")) before fetching the user. tsx Copy Edit const token = localStorage.getItem('auth_token'); console.log("Retrieved Token:", token); ➡️ If null, the login function may not be storing it correctly. 2️⃣ Login Mutation May Not Be Setting JWT Correctly Issue: Your loginMutation stores auth_token in localStorage, but some browsers block localStorage access in incognito/private mode. Fix: Ensure the token is stored before calling queryClient.setQueryData and prefetchQuery. Modify: tsx Copy Edit const loginMutation = useMutation({ mutationFn: async (credentials: LoginData) => { const res = await apiRequest("POST", "/api/login", credentials); if (!res.ok) { throw new Error("Login failed"); } const data = await res.json(); if (data.token) { console.log("Storing Token:", data.token); localStorage.setItem('auth_token', data.token); } return data; }, onSuccess: (user: SelectUser) => { console.log("Login successful:", user); queryClient.setQueryData(["/api/user"], user); }, onError: (error: Error) => { console.error("Login error:", error); }, }); ➡️ This ensures the token is stored before React Query updates the state. 3️⃣ Logout Not Clearing Cache Correctly Issue: queryClient.removeQueries({ queryKey: ["/api/user"] }) does not always trigger a re-render. Fix: Explicitly set the query data to null before removing. tsx Copy Edit const logoutMutation = useMutation({ mutationFn: async () => { const res = await apiRequest("POST", "/api/logout"); if (!res.ok) throw new Error("Logout failed"); localStorage.removeItem('auth_token'); // Clear token queryClient.setQueryData(["/api/user"], null); }, onSuccess: () => { console.log("User logged out successfully"); }, }); ➡️ This prevents stale session data after logout. 4️⃣ API Calls Not Sending Token Correctly Issue: The Authorization header might not be set correctly when making fetch requests. Fix: Ensure the token is included in every request. Modify: tsx Copy Edit const response = await fetch("/api/user", { headers: { 'Authorization': token ? `Bearer ${token}` : '', 'Content-Type': 'application/json', } }); ➡️ Ensure all API calls include the Authorization header. 5️⃣ React Query Cache Issues Issue: After login/logout, queryClient might be holding stale data. Fix: Force refetch after authentication events. tsx Copy Edit queryClient.invalidateQueries(["/api/user"]); ➡️ Forces the user state to refresh.