Firebase - Best way to always check if a user is logged in?

Viewed 8387

I'm working on a react project using Firebase and I was wondering what is the best way to always confirm that a user is logged in?

What I've currently been doing is on every landing page, check if the user is logged in and if the user is logged in, then proceed to the page and if no user is signed in, take the user to the login page.

However, I feel that there must be a more efficient way and I was wondering if anyone here is familiar with this?

Is using a store the optimal way here? E.g. check if a user is signed in once then updating the store and from there on, always ask the store if the user is signed in rather than pinging Firebase to see if a user is logged on.

Thanks for your help!

1 Answers

You should add a listener to onAuthStateChange, and do the appropriate action when logged in vs out. https://firebase.google.com/docs/auth/web/manage-users.

firebase.auth().onAuthStateChanged(function(user) {
if (user) {
  // User is signed in.
} else {
  // No user is signed in.
}
});
Related