DEV Community

Pratik Shah
Pratik Shah

Posted on

Deleting all Firebase users

There are 100's of zombie users in my Firebase account and I was looking for efficient way of deleting all Firebase users.

There are three ways in which we can delete users in Firebase

  1. Using Client SDK: in which we can only delete the current user account firebase.auth().currentUser?.delete();
  2. Login to Firebase console and delete user one by one from the web page. There is no bulk delete option.
  3. Delete all user at once using Admin SDK

I used third option because it is fastest. Let's go through steps of writing script to delete users using Admin SDK.

We need to write simple node.js script in which we will initialise Admin SDK and interact with Firebase in privileged environment.

Before this we will need to generate private key which is used in initialising Admin SDK. Below steps are copied form Firebase docs to generate key

To generate a private key file for your service account:

  1. In the Firebase console, open Settings > Service Accounts.
  2. Click Generate New Private Key, then confirm by clicking Generate Key.
  3. Securely store the JSON file containing the key.

Now we have the private key, lets start writing node script

Create a new folder. Run the following in terminal

npm init
sudo npm install firebase-admin --save
Enter fullscreen mode Exit fullscreen mode

Now create an index.js file in this folder and copy the below script. Replace serviceAccount file path and databaseURL.

const admin = require("firebase-admin");
const serviceAccount = require("./path/to/serviceAccountKey.json");
const databaseURL = "https://project-name.firebaseio.com"

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: databaseURL
});

const deleteAllUsers = (nextPageToken) => {
  let uids = []
  admin
    .auth()
    .listUsers(100, nextPageToken)
    .then((listUsersResult) => {
      uids = uids.concat(listUsersResult.users.map((userRecord) => userRecord.uid))
      console.log(uids)
      if (listUsersResult.pageToken) {
        deleteAllUsers(listUsersResult.pageToken);
      }
    })
    .catch((error) => {
      console.log('Error listing users:', error);
    }).finally(() => {
      admin.auth().deleteUsers(uids)
    })
};

deleteAllUsers();
Enter fullscreen mode Exit fullscreen mode

Above scripts fetch users in batch and collects uid of users. Which then are passed to deleteUsers function.

Above script will delete all the users in Firebase.

Top comments (1)

Collapse
 
thatgriffith profile image
Kevin H Griffith

Worked like a charm! Huge thanks! 🙏🔥