57

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 can help me out with this.

4
  • 1
    Based on what do you want to retrieve it? authenticated user? user email? please, more details..
    – adolfosrs
    Jul 13, 2016 at 13:25
  • 1
    The UID of any user, or the authenticated one?
    – Dominic
    Jul 13, 2016 at 14:18
  • Basically, I need to generate token from UID by Firebase.auth().createCustomToken(UID) to sign in user on firebase with the following function firebase.auth().signInWithCustomToken(token). Jul 14, 2016 at 15:47
  • are you trying to get the uid on the server or on the client?
    – dylanjha
    Nov 16, 2016 at 18:58

7 Answers 7

84

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

5
  • 1
    But I need UID to login user. Jul 14, 2016 at 15:54
  • 1
    I'm not sure what you mean, this will give you the UID of the logged in user. You can't get the UID of others.
    – Dominic
    Jul 14, 2016 at 16:15
  • This methods is not triggering at all for me. Feb 9, 2017 at 6:00
  • 3
    This is not a solution to the problem
    – user7319004
    Apr 6, 2019 at 7:50
  • @PiyushBansal The (mostly misnamed) "uid" is any value, in this case probably coming from the user input, e.g. a login form. It's not the Firebase user uid. So in this case it's probably the username that you want to login with. See my longer answer below. Feb 11, 2021 at 18:19
28

if a user is logged in then the console.log will print out:

if (firebase.auth().currentUser !== null) 
        console.log("user id: " + firebase.auth().currentUser.uid);
1
  • 2
    I was having an issue where this is not available immediately on page load. The callback method (onAuthStateChanged) worked for me though.
    – Fractaly
    Mar 8, 2019 at 3:15
9

on server side you can use firebase admin sdk to get all user information :

const admin = require('firebase-admin')
var serviceAccount = require("./serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://yourprojecturl.firebaseio.com",
});

admin.auth().listUsers().then(data=>{
    console.log(data.users)
})
4

This is an old question but I believe the accepted answer provides a correct answer to a different question; and although the answer from Dipanjan Panja seems to answer the original question, the original poster clarified later in a reply with a different question:

Basically, I need to generate token from UID by Firebase.auth().createCustomToken(UID) to sign in user on firebase with the following function firebase.auth().signInWithCustomToken(token).

Because the original question was clarified that the intent is to use createCustomToken and signInWithCustomToken, I believe this is a question about using the Firebase Admin SDK or Firebase Functions (both server-side) to provide custom authentication, probably based on a username and password combination, rather than using an email address and password.

I also think there's some confusion over "uid" here, where in the code example below, it does NOT refer to the user's Firebase uid, but rather the uid indicated in the doc for createCustomToken, which shows:

admin
  .auth()
  .createCustomToken(uid)
  .then((customToken) => {
    ...

In this case, the uid parameter on the createCustomToken call is not the Firebase uid field (which would not yet be known), thus providing a series of frustrating replies to the coder asking this question.

Instead, the uid here refers to any arbitrary basis for logging in for which this custom auth will support. (For example, it could also be an email address, social security number, employee number, anything...)

If you look above that short code block from the documentation page, you'll see that in this case uid was defined as:

const uid = 'some-uid';

Again, this could represent anything that the custom auth wanted it to be, but in this case, let's assume it's username/userid to be paired with a password. So it could have a value of 'admin' or 'appurist' or '123456' or something else.

Answer: So in this case, this particular uid (misnamed) is probably coming from user input, on a login form, which is why it is available at (before) login time. If you know who is trying to log in, some Admin SDK code code then search all users for a matching field (stored on new user registration).

It seems all of this is to get around the fact that Firebase does not support a signInWithUsernameAndPassword (arbitrary userid/username) or even a signInWithUidAndPassword (Firebase UID). So we need Admin SDK workarounds, or Firebase Functions, and the serverless aspect of Firebase is seriously weakened.

For a 6-minute video on the topic of custom auth tokens, I strongly recommend Jen Person's YouTube video for Firebase here: Minting Custom Tokens with the Admin SDK for Node.js - Firecasts

3

As of now in Firebase console, there is no direct API to get a list of users, Auth User(s) UID.
But inside your Firebase database, you can maintain the User UID at user level. As below,

"users": {
  "user-1": {
    "uid": "abcd..",
    ....
  },
  "user-2": {
    "uid": "abcd..",
    ....
  },
  "user-3": {
    "uid": "abcd..",
    ....
  }
}

Then you can make a query and retrieve it whenever you need uid's.
Hope this simple solution could help you!

3
  • 1
    Basically, I need to generate token from UID by Firebase.auth().createCustomToken(UID) to sign in user on firebase with the following function firebase.auth().signInWithCustomToken(token). Is there any other way to Sign In User on firebase ? Jul 14, 2016 at 15:48
  • Firebase makes authentication easy. It has built-in functionality for email & password, and third-party providers such as Facebook, Twitter, GitHub, and Google. And with Firebase custom Authentication API, you can integrate with your existing login server too.
    – Karthi R
    Jul 15, 2016 at 6:04
  • For more info go through these articles, hope this would help you, Link-1 and Link-2
    – Karthi R
    Jul 15, 2016 at 6:06
1

From Firebase docs, use Firebase.getAuth():

var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
var authData = ref.getAuth();

if (authData) {
  console.log("Authenticated user with uid:", authData.uid);
}

Source:

2
  • 1
    If I try it, authdata.uid belongs to which user? the problem is that I need UID to signin user on firebase and without authentication, how can I get the correct UID. Jul 14, 2016 at 15:50
  • I believe this belongs to the currently authenticated user, this can be easily confirmed against the DB..
    – Selfish
    Jul 14, 2016 at 16:06
0

This question is so old that the answers are outdated. the way to do access the user's UID is via the user.uid property in the user object when authenticate the user. Here is the code:

const handleSignUpWithGoogle = (isLoggedIn, navigation) => {
    signInWithPopup(auth, providerGoogle)
    .then((result) => {
      const credential = GoogleAuthProvider.credentialFromResult(result);
      const token = credential.accessToken;
      const user = result.user;
      isLoggedIn = !isLoggedIn
      console.log(isLoggedIn, **user.uid**)
      navigation.navigate('Home')
      alert('Signing in with google succeeded')
    }).catch((error) => {
      // Handle Errors here.
      const errorCode = error.code;
      const errorMessage = error.message;
      const email = error.customData.email;
      const credential = GoogleAuthProvider.credentialFromError(error);
      // ...
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.