Is there any way to get Firebase Auth User UID?

Piyush Bansal picture Piyush Bansal · Jul 13, 2016 · Viewed 83.3k times · Source

I am looking to fetch Auth User(s) UID from Firebase via NodeJS or Javascript API. I have attached screenshot for it so that you will have idea what I am looking for.

enter image description here

Hope, you guys help me out with this.

Answer

Dominic picture Dominic · Jul 13, 2016

Auth data is asynchronous in Firebase 3. So you need to wait for the event and then you have access to the current logged in user's UID. You won't be able to get the others. It will get called when the app opens too.

You can also render your app only once receiving the event if you prefer, to avoid extra logic in there to determine if the event has fired yet.

You could also trigger route changes from here based on the presence of user, this combined with a check before loading a route is a solid way to ensure only the right people are viewing publicOnly or privateOnly pages.

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User logged in already or has just logged in.
    console.log(user.uid);
  } else {
    // User not logged in or has just logged out.
  }
});

Within your app you can either save this user object, or get the current user at any time with firebase.auth().currentUser.

https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged