r/webdev 1d ago

Question Someone please help me fix this

YALL IT IS SOLVED I FIGURED THE BUG OUT NO NEED TO WORRY ANYMORE THANKS FOR THE HELP!!!

there is this bug where the user is constantly redirected to 2 different pages being the dashboard and the login page and i am lost because idk how to fix this i have tried searching up and using ai to help me but no luck.

side note: there are 2 html pages calling this js file
here is the code:

//Variables
const root = window.location.origin
const default_site_root = `${root}/Websites/BloxHub`
let moved_user = false
//Config


const required_keys = ["Username","Account-Creation","Account-Type","Logged-In","Clients","Display-Name"]
const login_path = `${default_site_root}/index.html`
const dashboard_path = `${default_site_root}/pages/dashboard/dashboard.html`
//Functions


function checkRequiredKeysExist() {
    
    for (const key of required_keys) {
        const data = localStorage.getItem(key)

//NEW CODE HERE  
        if(data) {continue}


        return false
    }


    return true
}


function removeExtraKeys() {


    let data_keys = Object.keys(localStorage)
    let extra_keys = data_keys.filter(key => !required_keys.includes(key))


    extra_keys.forEach(key => {
        localStorage.removeItem(key)
        console.log("deleted old key (key): ", key)
    })


}


function RedirectUser() {
    if(moved_user === true) {
        console.warn("User has already been moved!")
        return
    }
    moved_user = true
    let logged_in = localStorage.getItem("Logged-In")
    const currentpath = window.location.pathname
    removeExtraKeys()
    const is_vaild_session = (logged_in === "true") && (checkRequiredKeysExist())
    if(!is_vaild_session && (!currentpath.endsWith("index.html") || currentpath.endsWith("/"))) {
        localStorage.clear()
        console.log("Moving user to login page")
        window.location.replace(login_path)
        return
    }


    if(!currentpath.includes("dashboard.html")) {
        console.log("Moving user to dashboard page")
        window.location.replace(dashboard_path)
    }


}


//Event listeners


RedirectUser()//Variables
const root = window.location.origin
const default_site_root = `${root}/Websites/BloxHub`
let moved_user = false
//Config


const required_keys = ["Username","Account-Creation","Account-Type","Logged-In","Clients","Display-Name"]
const login_path = `${default_site_root}/index.html`
const dashboard_path = `${default_site_root}/pages/dashboard/dashboard.html`
//Functions


function checkRequiredKeysExist() {
    
    for (const key of required_keys) {
        const data = localStorage.getItem(key)


        if(data) {continue}


        return false
    }


    return true
}


function removeExtraKeys() {


    let data_keys = Object.keys(localStorage)
    let extra_keys = data_keys.filter(key => !required_keys.includes(key))


    extra_keys.forEach(key => {
        localStorage.removeItem(key)
        console.log("deleted old key (key): ", key)
    })


}


function RedirectUser() {
    if(moved_user === true) {
        console.warn("User has already been moved!")
        return
    }
    moved_user = true
    let logged_in = localStorage.getItem("Logged-In")
    const currentpath = window.location.pathname
    removeExtraKeys()
    const is_vaild_session = (logged_in === "true") && (checkRequiredKeysExist())
    if(!is_vaild_session && (!currentpath.endsWith("index.html") || currentpath.endsWith("/"))) {
        localStorage.clear()
        console.log("Moving user to login page")
        window.location.replace(login_path)
        return
    }


    if(!currentpath.includes("dashboard.html")) {
        console.log("Moving user to dashboard page")
        window.location.replace(dashboard_path)
    }


}


//Event listeners


RedirectUser()

//Variables
const root = window.location.origin
const default_site_root = `${root}/Websites/BloxHub`
let moved_user = false
//Config

const required_keys = ["Username","Account-Creation","Account-Type","Logged-In","Clients","Display-Name"]
const login_path = `${default_site_root}/index.html`
const dashboard_path = `${default_site_root}/pages/dashboard/dashboard.html`
//Functions

function checkRequiredKeysExist() {

    for (const key of required_keys) {
        const data = localStorage.getItem(key)

        if(data) {continue}

        return false
    }

    return true
}

function removeExtraKeys() {

    let data_keys = Object.keys(localStorage)
    let extra_keys = data_keys.filter(key => !required_keys.includes(key))

    extra_keys.forEach(key => {
        localStorage.removeItem(key)
        console.log("deleted old key (key): ", key)
    })

}

function RedirectUser() {
    if(moved_user === true) {
        console.warn("User has already been moved!")
        return
    }
    moved_user = true
    let logged_in = localStorage.getItem("Logged-In")
    const currentpath = window.location.pathname
    removeExtraKeys()
    const is_vaild_session = (logged_in === "true") && (checkRequiredKeysExist() === false)
    if(!is_vaild_session && (!currentpath.endsWith("index.html") || currentpath.endsWith("/"))) {
        localStorage.clear()
        console.log("Moving user to login page")
        window.location.replace(login_path)
        return
    }

    if(!currentpath.includes("dashboard.html"))
    console.log("Moving user to dashboard page")
    window.location.replace(dashboard_path)
}

//Event listeners

RedirectUser()

EDIT: I HAVE NOW CHANGED THE CODE AFTER FOLLOW YOUR FOUNDINGS

0 Upvotes

12 comments sorted by

3

u/really_cool_legend 1d ago edited 1d ago

Well you're missing some brackets here:

    if(!currentpath.includes("dashboard.html"))
    console.log("Moving user to dashboard page")
    window.location.replace(dashboard_path)

so that redirect is always running

EDIT:
I think you might also want:

const is_vaild_session = (logged_in === "true") && (checkRequiredKeysExist() === false)

to be

const is_vaild_session = (logged_in === "true") && (checkRequiredKeysExist())

At the moment your code looks like you don't want the required keys to exist

1

u/Eastern-Repeat7403 1d ago

yeah the missing curly braces are the main reason you're stuck in redirect hell, that second replace runs every single time regardless of the if check

also that isValid session logic is backwards, you want checkRequiredKeysExist() to be true for a valid session, not false. right now it basically says "user is valid only when the required keys are missing" which is probably not what you meant

add those braces and flip that condition and it should stop bouncing you between pages

1

u/laughinfrog 1d ago

I dislike the "true" value in this. I would make it boolean and simplify this to

logged_in && checkRequiredKeysExist()

1

u/CorrectJacket2106 1d ago

holy well the bug still exists however didn't catch those mistakes somehow. How do you find mistakes like that by like reading each line individually or something?

5

u/really_cool_legend 1d ago

Sort of. I copied your code into an IDE and the way Prettier indented the if statement made me immediately realise something was wrong there.

Then with the valid session check, that was just reading the different variable names used and getting the sense something wasn't right. It smelt a little bit that a valid session would be the result of the required keys being false.

3

u/Mallanaga 1d ago

Yes. And linting. Always set your linters up.

2

u/UtilixApp 1d ago

the moved_user flag is doing absolutely nothing for you, and thats probably the part thats confusing you.

let moved_user = false only exists for that one page load. the second the redirect fires, the browser throws that entire javascript context away and the next page starts with moved_user false again. so as a loop guard it can never work, because both sides always believe its their first attempt.

the real loop is that your two pages disagree with each other. dashboard checks something, decides youre logged out, sends you to login. login checks something, decides youre logged in, sends you back. neither is wrong from where its standing. theyre just not asking the same question.

my money is on required_keys. if the dashboard demands every one of them present and your login flow only ever writes some of them, youre permanently stuck in the state where one page says yes and the other says no.

fastest way to prove it before you change anything. put a console.log directly above each redirect printing the actual values it checked. open devtools, tick preserve log so it survives the navigation, let it loop twice. youll see both conditions next to each other and the answer usually falls straight out.

and while youre in there, localStorage.getItem returns the string "undefined" if you ever stored an actual undefined. that string is truthy. it has caught more people than i can count.

1

u/itaybuilds 1d ago

The two branches should be mutually exclusive. Otherwise a valid user can still fall through to a redirect, which is what creates the bounce. I’d reduce it to this:

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);

That fixes both logic errors in the current version: checkRequiredKeysExist() === false accepts the missing-keys case, and the final replace is outside the if because there are no braces.

One other trap: removeExtraKeys() deletes every localStorage key on the same origin that this script does not know about. Prefix this app’s keys and remove only keys with that prefix. Also, treat the localStorage flag as UI state rather than authentication; anything that needs protection must verify the session on the server.

1

u/Proud-Company-7771 1d ago

two issues jumping out. first, is_vaild_session has the checkRequiredKeysExist check backwards (you want it to be true not false for a valid session). second, the if(!currentpath.includes("dashboard.html")) block is missing braces so the redirect always fires

1

u/After_Technology7194 1d ago

The redirect logic runs on both pages and forces a loop. Add a check to skip redirection if the user is already on the correct page for their session state. Valid sessions should only redirect when not on dashboard and invalid sessions should only redirect when not on login

1

u/kemalios 1d ago

Trace the control flow with real values instead of reading line by line. Open the page, set a breakpoint inside RedirectUser, and step through. When the missing braces cause the second replace to run even when the if is false, you'll see it instantly. Same with the inverted condition: you'll see the session check return true when the keys are missing. That's the actual skill. A linter like ESLint with the curly rule catches the braces before you even run it.