I have the same JavaScript file loaded by both my login page and dashboard page. It checks localStorage for a Logged-In flag and several required keys, then redirects users to either the login page or dashboard. Instead, the browser keeps bouncing between the two pages. I have already tried changing the session condition, but I still do not understand what is causing the loop or how to debug this kind of issue.
4 Answers
Try simplifying the whole decision tree instead of having two independent redirects:
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) window.location.replace(login_path);
return;
}
if (!onDashboard) {
window.location.replace(dashboard_path);
}
This makes the two states clear: invalid sessions belong on login, and valid sessions belong on the dashboard. Also, `moved_user` cannot prevent a cross-page loop because it is reset to false whenever the browser loads the next page.
Use the browser's developer tools to see which condition is failing instead of guessing. Log the values immediately before each redirect, including Logged-In, the result of checkRequiredKeysExist(), and currentpath. Enable Preserve log in the console so messages remain visible after navigation. You may discover 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 same site.
The localStorage flag is only client-side UI state, not real authentication. It is fine for deciding which page to display in a small project, but anything that actually protects user data needs server-side session validation. For debugging this issue, first clear localStorage, log in again, and confirm that all six required keys are written with the expected values. In particular, Logged-In must be the string "true", because localStorage stores strings.
There are two important logic problems. First, the redirect to the dashboard is missing braces, so only the first statement is controlled by the if. The location.replace call runs every time:
if (!currentpath.includes("dashboard.html")) {
console.log("Moving user to dashboard page");
window.location.replace(dashboard_path);
}
Second, a valid session should require the required keys to exist. Use checkRequiredKeysExist(), not checkRequiredKeysExist() === false. Your login and dashboard decisions should also be mutually exclusive so a valid user is sent to the dashboard only when they are not already there, while an invalid user is sent to login only when they are not already on the login page.

The loop still confused me after making those changes. Is the usual way to find this kind of mistake just reading every line carefully?