skip to Main Content

In my app, I allow my users revoke their access. So when a user is deleted from the Firebase Authentication, I have a function that deletes the user from Firestore:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.deleteUser = functions.auth.user().onDelete((user) => {
  const uid = user.uid;

  return admin
      .firestore()
      .collection("users")
      .doc(uid)
      .delete();
});

Which works fine. The problem is that I want to delete the profile picture that is stored in Firebase Storage at: images/uid.png as well. So how to delete the document in Firestore together with the image in Storage, only if the image exists? Thanks in advance.

2

Answers


  1. You can use the Admin SDK for Cloud Storage (API documentation) as follows:

    exports.deleteUser = functions.auth.user().onDelete(async (user) => {
    
        try {
            const uid = user.uid;
    
            await admin
                .firestore()
                .collection("users")
                .doc(uid)
                .delete();
    
            const file = admin.storage().bucket().file(`images/${uid}.png`);
            const fileExists = await file.exists();
            if (fileExists) {
                await file.delete();    
            }
            
            return true;
            
        } catch (error) {
            console.log(error);
            return true;
        }
    });
    

    Note that you could also use the Delete User Data extension which is exactly done for this case: "Deletes data keyed on a userId from Cloud Firestore, Realtime Database, or Cloud Storage when a user deletes their account. "

    Login or Signup to reply.
  2. Why don’t you delete your picture with the user deletion?

    
    exports.deleteUser = functions.auth.user().onDelete((user) => {
      const uid = user.uid;
      const picture = admin.storage().bucket().file(`images/${uid}.png`);
    
      return picture
        .exists()
        .then(() => imageRef.delete())
        .finally(() => admin.firestore().collection("users").doc(uid).delete());
    });
    

    Note, if the image doesn’t exist, it will throw an error. But the finally will handle it properly in order to run the deletion.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search