简体   繁体   中英

Firebase Web redirect user to login page

Trying to simply redirect the users who are authenticated to home.html and those who are not to login.html via Firebase.

firebase.auth().onAuthStateChanged(function (user) {
  if (user) {
    console.log('SIGNED IN');
    window.location.href = "home.html"; // <-- This is not good...
  } else {
    console.log('NOT SIGNED IN');
  }
});

Everyone says to use this bit of code, and it does work to keep track if the user is logged in, but if I put that line inside the if check it will just cause an infinite loop constantly redirecting the browser to the home page once the user is authenticated.

Is there something simple I missed?

The code you're showing will redirect any time the auth state changes to show there's a user present. And that will trigger in any page being loaded, as the SDK doesn't know ahead of the page load if the user is logged in. The SDK has to wait for an init to complete in order to trigger the listener. So, it sounds like that's not what you want.

What you'll have to do is define specifically at what point in your app that you want a redirect to happen, and make sure that condition and timing is met before you redirect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM