I have a JavaScript file loaded by both my login page and dashboard page. It checks localStorage for a Logged-In flag and several required account keys, then redirects invalid sessions to index.html and valid sessions to dashboard.html. Instead, the browser keeps bouncing between the two pages. I have already revised the code, but I still do not understand what is causing the loop or how to debug this kind of logic.
4 Answers
There are two main logic problems. First, your session check is backwards in the revised code: `checkRequiredKeysExist() === false` treats missing required keys as a valid session. It should be `checkRequiredKeysExist()` or `checkRequiredKeysExist() === true`. Second, this block has no braces: `if (!currentpath.includes("dashboard.html")) console.log(...); window.location.replace(dashboard_path);` Only the log is controlled by the if, so the redirect runs every time. Use braces around both statements. Also, `moved_user` cannot prevent a navigation loop because it resets to false when the next page loads.
Use the browser console to find out which condition is wrong instead of guessing. Log `currentpath`, `logged_in`, the result of `checkRequiredKeysExist()`, `hasSession`, `onLogin`, and `onDashboard` immediately before each redirect. 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. Also be careful with `removeExtraKeys()`: it deletes every localStorage entry that is not in your list, including data belonging to other parts of the site. Prefix your app's keys and only remove matching entries.
The `Logged-In` localStorage value should only control the client-side display. It is not secure authentication because users can edit localStorage freely. Anything that protects an account or private data should validate the session on the server. For the immediate loop, though, make both pages use exactly the same session condition and only redirect when the current page is not already the correct destination.
Make the session branches mutually exclusive and explicitly identify which page is open. 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);` Invalid sessions stay on the login page, while valid sessions stay on the dashboard. This prevents the second redirect from running after the first condition has already handled the request.

The loop still happened after I changed those lines. What is a good way to spot mistakes like this instead of manually rereading every line?