Skip to content Skip to sidebar Skip to footer

Firebase Total User Count

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.

Solution 1:

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());
});

Solution 2:

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);
});

Solution 3:

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)


Solution 4:

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
});

Post a Comment for "Firebase Total User Count"