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
You can use the Admin SDK for Cloud Storage (API documentation) as follows:
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. "
Why don’t you delete your picture with the user deletion?
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.