Batch Delete Firebase Users Using Golang

Narayan Shrestha
readytowork, Inc.
Published in
4 min readSep 23, 2023

Firebase, a popular mobile and web application development platform, offers a robust suite of services, including Firebase Authentication, which simplifies user management. As your application grows, efficient user management becomes essential. One common task is batch deleting users for various reasons, such as account cleanup, security breaches, or user data retention policies.

In this article, we’ll explore how to batch delete Firebase users using the Go programming language (Golang). We’ll leverage the Firebase Admin SDK for Go to interact with Firebase Authentication and perform batch user deletions. This guide is tailored for developers and system administrators who need to manage Firebase users at scale.

Prerequisites

Before we dive into batch user deletion, ensure you have the following prerequisites in place:

  1. Firebase Account: You should have a Firebase project set up and access to the Firebase console.
  2. Golang Installed: You need Go (Golang) installed on your system. You can download and install Go from the official website.
  3. Firebase Admin SDK: Install the Firebase Admin SDK for Go in your project. You can find installation instructions in the official Firebase Admin SDK documentation.

Initializing Firebase Admin SDK in Go

The Firebase Admin SDK allows you to interact with various Firebase services programmatically. To get started, initialize the Firebase Admin SDK with your service account credentials. These credentials, stored in a JSON file, are required for authentication and authorization.

Here’s how you can initialize the Firebase Admin SDK in Go:

// Initialize Firebase Admin SDK
ctx := context.Background()
opt := option.WithCredentialsFile("path/to/serviceAccountKey.json")
app, err := firebase.NewApp(ctx, nil, opt)
if err != nil {
log.Fatalf("Error initializing Firebase Admin SDK: %v", err)
}
// Get the Auth client
client, err := app.Auth(ctx)if err != nil {
log.Fatalf("Error getting Auth client: %v", err)
}

With the Firebase Admin SDK initialized, you’re ready to perform batch user deletions efficiently.

Retrieving User Data

Before you can delete users in bulk, you need to retrieve their data from Firebase Authentication. The Firebase Admin SDK provides a convenient method, client.Users, to retrieve user records. You can optionally specify a page token for pagination, but for simplicity, we'll retrieve all user records in this example.

// Retrieve a list of all user UIDs
iter := client.Users(context.Background(), "")
var userUIDs []string
for {
user, err := iter.Next()
if err != nil {
if err == iterator.Done {
break // All available users have been retrieved
}
log.Printf("Error retrieving user: %v", err)
break
}
if user != nil {
userUIDs = append(userUIDs, user.UID)
}
}
// Now you have a list of user UIDs in the userUIDs slice.

Deleting Users in Batches

To delete users in batches, we’ll implement a function that takes care of the process. In this example, we’ll delete users in batches of a specified size. Here’s the code for batch deletion:

func deleteUsersInBatch(client *auth.Client, userUIDsToDelete []string, batchSize int) {
for i := 0; i < len(userUIDsToDelete); i += batchSize {
end := i + batchSize
if end > len(userUIDsToDelete) {
end = len(userUIDsToDelete)
}
batch := userUIDsToDelete[i:end]
_, err := client.DeleteUsers(context.Background(), batch)
if err != nil {
for _, uid := range batch {
log.Printf("Error deleting user %s: %v", uid, err)
}
} else {
for _, uid := range batch {
log.Printf("Deleted user %s successfully", uid)
}
}
}
}

Wrapping up, here is the final code.
Create a file name main.go paste the following part:

package main

import (
"context"
"log"
firebase "firebase.google.com/go/v4"
"firebase.google.com/go/v4/auth"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)

func main() {
// Initialize Firebase Admin SDK
ctx := context.Background()

opt := option.WithCredentialsFile("./serviceAccountKey.json")
app, err := firebase.NewApp(ctx, nil, opt)
if err != nil {
log.Fatalf("Error initializing Firebase Admin SDK: %v", err)
}

// Get the Auth client
client, err := app.Auth(ctx)
if err != nil {
log.Fatalf("Error getting Auth client: %v", err)
}
userUIDs := getAllUserUIDs(client, 2000)

for _, uid := range userUIDs {
log.Printf("User UID: %s", uid)
}
deleteUsersInBatch(client, userUIDs, 200)
}

func deleteUsersInBatch(client *auth.Client, userUIDsToDelete []string, batchSize int) {
for i := 0; i < len(userUIDsToDelete); i += batchSize {
end := i + batchSize
if end > len(userUIDsToDelete) {
end = len(userUIDsToDelete)
}
batch := userUIDsToDelete[i:end]
_, err := client.DeleteUsers(context.Background(), batch)
if err != nil {
for _, uid := range batch {
log.Printf("Error deleting user %s: %v", uid, err)
}
} else {
for _, uid := range batch {
log.Printf("Deleted user %s successfully", uid)
}
}
}
}

func removeUserByID(userUIDs []string, idToRemove string) []string {
var filteredUIDs []string
for _, uid := range userUIDs {
if uid != idToRemove {
filteredUIDs = append(filteredUIDs, uid)
}
}
return filteredUIDs
}

func getAllUserUIDs(client *auth.Client, size int) []string {
// Retrieve a list of all user UIDs
iter := client.Users(context.Background(), "")
var userUIDs []string
for i := 0; i < size; i++ {
user, err := iter.Next()
if err != nil {
if err == iterator.Done {
break
}
log.Printf("Error retrieving user: %v", err)
break
}
if user != nil {
userUIDs = append(userUIDs, user.UID)
}

return userUIDs
}

Now, run “go run main.go

Hope it helps. Happy Coding

--

--