I have the same JavaScript file running on both my login page and dashboard page. It checks several localStorage values to decide whether the user has a valid session, then redirects invalid users to the login page and valid users to the dashboard. Instead, the browser keeps bouncing between the two pages. I have already edited the code, but I am still unsure what is causing the loop or how to debug this kind of issue.
3 Answers
There are two main logic problems. First, the required-key check is reversed in the edited version. A valid session should use `checkRequiredKeysExist()` or `checkRequiredKeysExist() === true`, not `=== false`. Second, this block needs braces: `if (!currentpath.includes("dashboard.html")) { window.location.replace(dashboard_path); }`. Without braces, only the next statement belongs to the `if`, so the redirect runs on every page. Also, `moved_user` cannot prevent a cross-page loop because it is reset whenever the browser loads the next document.
Use DevTools to find out which condition is disagreeing between the pages. Log the values immediately before each redirect, including `currentpath`, `logged_in`, `checkRequiredKeysExist()`, and `isValidSession`. Enable the console's Preserve log option so the messages remain visible after navigation. You may find that one page is missing one of the required localStorage keys, causing the two pages to make opposite decisions. Also be careful with `removeExtraKeys()`: it deletes every localStorage key on that origin that is not in your list, including data belonging to other parts of the site.
Make the session branches mutually exclusive so each page only redirects when it is not already the correct page. For example: `const hasSession = localStorage.getItem("Logged-In") === "true" && checkRequiredKeysExist(); const onLogin = currentpath.endsWith("/index.html") || currentpath.endsWith("/"); const onDashboard = currentpath.endsWith("/dashboard.html"); if (!hasSession) { if (!onLogin) location.replace(login_path); return; } if (!onDashboard) location.replace(dashboard_path);` This prevents a valid user from falling through to the login redirect and prevents an invalid user from being sent to the dashboard.

The loop is still happening after I changed those parts. Is the usual way to find mistakes like this just reading every line, or is there a better debugging method?