Firebase Version 9 Tutorial (Modular)

Firebase Version 8 Tutorial (Namespaced)

Firebase 9 Auth → Sign Out A User Explained In A Minute [2024]

Last modified on June 6th, 2024
Raja Tamil
Authentication Firebase Javascript

In this Firebase 9 (the latest version) Authentication tutorial, learn how to log out/sign out a user using the signOut() method.

The signOut() is one of the 4 important methods that the Firebase Authentication SDK offers to build a user authentication system in minutes.

  1. createUserWithUserNameAndPassword()
  2. onAuthStateChanged()
  3. signInWithEmailAndPassword()
  4. signOut() → you’re here

The signOut() method allows users to sign out or log out of their current authentication session by ending the validation of the user’s authentication token provided at the time of signing in.

1. Initialize Firebase SDK To Your Web App

Before going any further, I assume that you already know how to initialize Firebase SDK in your JavaScript web app.

I also assume that you already know how to sign in to a user account using the Firebase Authentication back-end.

2. Import getAuth & signOut Methods

Import the Firebase Authentication SDK library via either NPM or CDN (I use CDN in the below example) and destructure the getAuth() and signOut() methods.

import {
  getAuth,
  signOut,
} from "https://www.gstatic.com/firebasejs/10.0.0/firebase-auth.js";

In order to implement any of the Firebase Authentication methods, first we need to create an instance of an authentication object.

const auth = getAuth();

3. Create a Sign-Out Button

Typically, you will want to call the signOut() method when a user clicks the sign-out button to sign out their current authenticated session after successfully signing in.

<button id="signOutBtn">Sign out</button>

Next, create a DOM reference for the sign-out button element.

const signOutBtn = document.getElementById("signOutBtn");

Then attach a click event with the callback function signOutButtonPressed to the sign-up button.

const signOutButtonPressed = (e) => {
  e.preventDefault();
  console.log("Sign out Button Pressed");
}

signOutBtn.addEventListener("click", signOutButtonPressed);

4. Call signOut() Method

Inside the signOutButtonPressed function, call the signOut() method.

const signOutButtonPressed = (e) => {
  e.preventDefault();
  signOut();
};

The signOut() method takes a single argument which is the authentication object that I’ve declared above.

const signOutButtonPressed = (e) => {
  e.preventDefault();
  signOut(auth);
};

The signOut() method is an asynchronous method that returns a promise which can be either fulfilled or rejected.

So add the await/async keywords to it.

const signOutButtonPressed = async(e) => {
  e.preventDefault();
  await signOut(auth);
};

To capture any errors, wrap the signOut() method with a try-catch block.

try {
    await signOut(auth);
    console.log("User Signed Out Successfully!");
  } catch (error) {
    console.log(error.code);
  }