🔍 Potential Issues and Fixes
1️⃣ Local Storage Token Not Persisting Correctly
Issue: The JWT token may not be set correctly in localStorage or retrieved before making API requests.
Fix: Ensure that the token is stored before updating React Query.
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();
    console.log("Login response data:", data);

    if (data.token) {
      localStorage.setItem("auth_token", data.token);
      console.log("Token stored in localStorage:", data.token);
    } else {
      throw new Error("Token missing in response");
    }

    return data;
  },
  onSuccess: (data) => {
    const { token, ...userData } = data;
    queryClient.setQueryData(["/api/user"], userData);
    setLocation("/");
  },
});
➡️ Test: Check the browser’s localStorage using console.log(localStorage.getItem("auth_token")) after login.

2️⃣ Fetching User Data Without Token
Issue: The fetch("/api/user") call might run before the token is set in localStorage.
Fix: Ensure the token is present before making requests.
tsx
Copy
Edit
const token = localStorage.getItem("auth_token");
if (!token) {
  console.warn("No token found, skipping user fetch");
  return null;
}

const response = await fetch("/api/user", {
  headers: { Authorization: `Bearer ${token}` },
});
➡️ Test: Check console.log("Token in useQuery:", token); to see if it's missing.

3️⃣ Logout Not Clearing Cache Properly
Issue: queryClient.clear() might not fully reset the cache.
Fix: Explicitly remove the user from React Query cache before clearing.
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");
    queryClient.setQueryData(["/api/user"], null);
    queryClient.clear();
  },
  onSuccess: () => {
    setLocation("/auth");
  },
});
➡️ Test: After logging out, check if localStorage.getItem("auth_token") is null.

4️⃣ Session Expiry Not Handled
Issue: If the token expires, the app does not automatically log the user out.
Fix: Check token expiration and remove if invalid.
Modify useQuery:

tsx
Copy
Edit
const token = localStorage.getItem("auth_token");

if (!token) return null;

try {
  const decoded = JSON.parse(atob(token.split(".")[1])); // Decode JWT payload
  if (decoded.exp * 1000 < Date.now()) {
    console.warn("Token expired, logging out...");
    localStorage.removeItem("auth_token");
    queryClient.setQueryData(["/api/user"], null);
    return null;
  }
} catch (err) {
  console.error("Error decoding token:", err);
}
➡️ Test: Use an expired token and see if it correctly logs out.

5️⃣ Backend JWT Verification Issue
Issue: The authenticateJWT middleware might not be properly validating the token.
Fix: Ensure the backend correctly verifies tokens.
Modify:

ts
Copy
Edit
function authenticateJWT(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization;

  if (!authHeader) {
    return res.status(401).json({ message: "No token provided" });
  }

  const token = authHeader.split(" ")[1];

  jwt.verify(token, JWT_SECRET, (err, decoded) => {
    if (err) {
      console.error("JWT verification failed:", err.message);
      return res.status(403).json({ message: "Invalid or expired token" });
    }

    req.user = decoded;
    next();
  });
}
➡️ Test: Check API logs for JWT verification failed errors.