How to Sign Out User in Firebase: Simple Guide
To sign out a user in Firebase, call the
signOut() method on the Firebase Authentication instance. This method ends the user's session and returns a promise that resolves when sign-out is complete.Syntax
The basic syntax to sign out a user in Firebase Authentication is:
firebase.auth().signOut()in Firebase Web SDK v8 and earlier.signOut(getAuth())in Firebase Modular Web SDK v9 and later.
This method returns a promise that resolves when the user is successfully signed out.
javascript
import { getAuth, signOut } from "firebase/auth"; const auth = getAuth(); signOut(auth).then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });
Example
This example shows how to sign out the current user using Firebase Modular SDK (v9+). It handles success and error cases with simple console messages.
javascript
import { initializeApp } from "firebase/app"; import { getAuth, signOut } from "firebase/auth"; const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", projectId: "YOUR_PROJECT_ID", // other config }; const app = initializeApp(firebaseConfig); const auth = getAuth(app); function logoutUser() { signOut(auth) .then(() => { console.log("User signed out successfully."); }) .catch((error) => { console.error("Error signing out:", error); }); } logoutUser();
Output
User signed out successfully.
Common Pitfalls
Common mistakes when signing out users include:
- Not calling
signOut()on the correct auth instance. - Ignoring the promise returned by
signOut(), which can cause missed errors. - Trying to sign out when no user is signed in, which is safe but unnecessary.
Always handle the promise to catch errors and confirm sign-out.
javascript
/* Wrong way: ignoring promise */ firebase.auth().signOut(); /* Right way: handle promise */ firebase.auth().signOut().then(() => { console.log("Signed out"); }).catch((error) => { console.error("Sign out error", error); });
Quick Reference
Remember these key points when signing out users in Firebase:
- Use
signOut(auth)with the Modular SDK. - Always handle the returned promise.
- Signing out clears the current user session.
Key Takeaways
Use the
signOut() method on the Firebase Auth instance to sign out users.Always handle the promise returned by
signOut() to catch errors.Use the Modular SDK syntax (
signOut(auth)) for new Firebase projects.Signing out ends the user's session and updates the app state accordingly.
Avoid ignoring sign-out errors to ensure smooth user experience.