Tal Amos
Tal Amos

Reputation: 123

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

Upvotes: 3

Views: 3817

Answers (1)

gegobyte
gegobyte

Reputation: 5545

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.

Upvotes: 3

Related Questions