Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a function that deletes user from Firestore and file from Storage?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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. "

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading