14

Is there a way to get all the users' count in firebase? (authenticated via password, facebook, twitter, etc.) Total of all social and email&password authenticated users.

5 Answers 5

8

There's no built-in method to do get the total user count.

You can keep an index of userIds and pull them down and count them. However, that would require downloading all of the data to get a count.

{
  "userIds": {
    "user_one": true,
    "user_two": true,
    "user_three": true 
  }
}

Then when downloading the data you can call snapshot.numChildren():

var ref = new Firebase('<my-firebase-app>/userIds');
ref.once('value', function(snap) {
  console.log(snap.numChildren());
});

If you don't want to download the data, you can maintain a total count using transactions.

var ref = new Firebase('<my-firebase-app>');
ref.createUser({ email: '', password: '', function() {
  var userCountRef = ref.child('userCount');
  userCountRef.transaction(function (current_value) {
    // increment the user count by one
    return (current_value || 0) + 1;
  });
});

Then you can listen for users in realtime:

var ref = new Firebase('<my-firebase-app>/userCount');
ref.on('value', function(snap) {
  console.log(snap.val());
});
4
  • So you say I can't really rely on firebase's user auth system and I have to create something to save new userids all the time. Do I understand correctly? Dec 6, 2015 at 11:04
  • 1
    Firebase authentication works only for authenticating users. If you want to do something with that data you store it in your Firebase database.
    – David East
    Dec 7, 2015 at 13:15
  • ok, fair enough. I would like to have access to at least all user ids or something like that though :) I'm accepting this as an answer Dec 7, 2015 at 20:22
  • For transaction, you can't ensure how user(hacker) manipulate the figure
    – tom10271
    Aug 2, 2017 at 4:33
7

Update 2021

I stumbled on this question and wanted to share three methods to get total number of signed-up users.

👀 Looking in the console

Go to the console, under Authentication tab, you can directly read the number of users under the list of users: enter image description here 56 users! yay!

📜 Using the admin SDK

For programmatic access to the number of users with potential filter on provider type, registration date, last connection date... you can write a script leveraging listUsers from the admin SDK.
For example, to count users registered since March 16:

const admin = require("firebase-admin");
const serviceAccount = require("./path/to/serviceAccountKey.json");
admin.initializeApp({ credential: admin.credential.cert(serviceAccount) });

async function countUsers(count, nextPageToken) {
    const listUsersResult = await admin.auth().listUsers(1000, nextPageToken);

    listUsersResult.users.map(user => {
        if (new Date(user.metadata.creationTime) > new Date("2021-03-16T00:00:00")) {
            count++;
        }
    });

    if (listUsersResult.pageToken) {
        count = await countUsers(count, listUsersResult.pageToken);
    }

    return count;
}

countUsers(0).then(count => console.log("total: ", count));

💾 Storing users in a DB

Your app maybe already stores user documents in Firestore, or the Realtime Database, or any other database. You can count these records to get the total number of registered users. (If you use Firestore, you can read my article on how to count documents)

6

Using Cloud Functions:

exports.updateUserCount = functions.auth.user().onCreate(user => {
  return admin.database().ref('userCount').transaction(userCount => (userCount || 0) + 1);
});

Just note that a Cloud Functions event is not triggered when a user is created using custom tokens. In that case, you would need to do something like this:

exports.updateUserCount = functions.database.ref('users/{userId}').onCreate(() => {
  return admin.database().ref('userCount').transaction(userCount => (userCount || 0) + 1);
});
4

Its mid 2022 now, and as far as I can tell, the required capability is still not the Node.js admin SDK, but it is available from the identity toolkit REST api.

The suggestion from Louis Coulet of looking at the Firebase console is what tipped me off. Looking at the console's API calls, we can see there is a "query" endpoint that can return the number of accounts.

The endpoint is documented here : https://cloud.google.com/identity-platform/docs/reference/rest/v1/projects.accounts/query

The admin SDK can provide the required access token to call the endpoint. See https://firebase.google.com/docs/reference/admin/node/firebase-admin.app.credential.md#credentialgetaccesstoken

firebase.initializeApp();
firebase.app().options.credential.getAccessToken().then(the_token => ...)

As the console does, we provide an empty query expression and set the returnUserInfo flag to false

curl --request POST \
  --url 'https://identitytoolkit.googleapis.com/v1/projects/your_project_goes_here/accounts:query?alt=json' \
  --header 'Content-Type: application/json' \
  --header 'authorization: Bearer the_token' \
  --data '{
    "returnUserInfo": false,
    "expression": []
}'

The query result is the number of accounts

{
  "recordsCount": "1223"
}

2
  • For this to work, your firebase project must be upgraded to use the Identity Platform. Sep 3, 2022 at 10:44
  • No it doesn't. Firebase auth uses identity platform behind the scenes. You can access the apis directly without having to upgrade anything. You can also get the access token mentioned above through api call, completely avoiding SDK usage in your app (if you want to).
    – Yigit Erol
    Sep 22, 2023 at 12:04
0

Here is a javascript Module for this purpose - https://gist.github.com/ajaxray/17d6ec5107d2f816cc8a284ce4d7242e

In single line, what it does is -

Keep list (and count) of online users in a Firebase web app - by isolated rooms or globally

For counting all users using this module -

firebase.initializeApp({...});
var onlineUsers = new Gathering(firebase.database());
gathering.join();

// Attach a callback function to track updates
// That function will be called (with the user count and array of users) every time user list updated
gathering.onUpdated(function(count, users) {
    // Do whatever you want
});

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.