Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make page only accessible if logged in - Firebase Web

Looking to get some help with a little bit of code to include on a page I want to be only accessed by logged in users and if a user is not logged in they can be redirected to the login page or log in on the same locked page.

Cheers

like image 715
Tal Amos Avatar asked Nov 28 '25 15:11

Tal Amos


1 Answers

Always use onAuthStateChanged() to keep track of the user's login or logout status.

//Handle Account Status
firebase.auth().onAuthStateChanged(user => {
  if(!user) {
    window.location = 'login.html'; //If User is not logged in, redirect to login page
  }
});

The above code will make sure that if a user is not signed in, they will be redirected to login page and if they are signed in, they will stay on the current page.

like image 177
gegobyte Avatar answered Dec 01 '25 04:12

gegobyte