How to Delete User in Firebase: Simple Guide
To delete a user in Firebase, use the
delete() method on the currently signed-in user object from Firebase Authentication. This removes the user account permanently from Firebase.Syntax
The basic syntax to delete a user in Firebase Authentication is:
firebase.auth().currentUser.delete()- Deletes the currently signed-in user.
This method returns a promise that resolves when the user is deleted.
javascript
firebase.auth().currentUser.delete() .then(() => { console.log('User deleted successfully'); }) .catch((error) => { console.error('Error deleting user:', error); });
Output
User deleted successfully
Example
This example shows how to delete the currently signed-in user and handle success or error.
javascript
import { getAuth } from 'firebase/auth'; const auth = getAuth(); const user = auth.currentUser; if (user) { user.delete() .then(() => { console.log('User deleted successfully'); }) .catch((error) => { console.error('Error deleting user:', error); }); } else { console.log('No user is signed in'); }
Output
User deleted successfully
Common Pitfalls
- User must be signed in: You can only delete the currently signed-in user. If no user is signed in, deletion will fail.
- Recent login required: Firebase may require the user to have recently signed in to delete their account. If not, you must reauthenticate the user before deleting.
- Handle errors: Always catch errors to handle cases like network issues or permission problems.
javascript
/* Wrong way: Trying to delete without a signed-in user */ const user = null; // user.delete(); // This will throw an error /* Right way: Check user and reauthenticate if needed */ if (user) { user.delete().catch(error => { if (error.code === 'auth/requires-recent-login') { // Prompt user to reauthenticate then delete } }); }
Quick Reference
Remember these key points when deleting a Firebase user:
- Use
currentUser.delete()to delete the signed-in user. - Ensure the user is signed in before calling delete.
- Reauthenticate if Firebase requires recent login.
- Handle errors gracefully to improve user experience.
Key Takeaways
Use currentUser.delete() to remove the signed-in user from Firebase Authentication.
The user must be signed in and may need to reauthenticate before deletion.
Always handle errors to manage permission or network issues.
Check if a user is signed in before attempting deletion to avoid errors.