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
- Using Client SDK: in which we can only delete the current user account
firebase.auth().currentUser?.delete();
- Login to Firebase console and delete user one by one from the web page. There is no bulk delete option.
- 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:
- In the Firebase console, open Settings > Service Accounts.
- Click Generate New Private Key, then confirm by clicking Generate Key.
- 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
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();
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 (2)
Thanks a lot!
If someone is new to running scripts:
To create index.js -
touch index.js
-> then open in redactor and add script.If serviceAccount is in the root of your Mac, then the path is:
./serviceAccountKey.json
To run script:
package.json
:"scripts": { "start": "node index.js" }
npm start
in terminalWorked like a charm! Huge thanks! ππ₯