redirect user if not logged in (Firebase/ Vanila JS)

Viewed 57

Good night, I need help with a problem that I'm not able to solve, I have a site with the index, register and login page, my problem is that I want that when the user is logged out he is redirected to the registration page if no, it is redirected to index, but I'm not able to do this without generating an infinite loop, could someone help me?

Meu código

firebase.auth().onAuthStateChanged(user => {

if (user) {
    var uid = user.uid;
    console.log("usuario conectado")
    
} else {
   window.location = 'register.html'
}})
1 Answers

I think you should check the current location that the user currently is before doing redirect.

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    var uid = user.uid;
    console.log("usuario conectado")
    
} else {
  if (window.location.pathname === '/login.html') return // user is in login page, skip.
  if (window.location.pathname !== '/register.html') {
    window.location = 'register.html'
  }
 }
}
Related