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