Firebase Version 9 Tutorial (Modular)

Firebase Version 8 Tutorial (Namespaced)

Firebase 9 Auth →  onAuthStateChanged Explained [2023]

Last modified on February 6th, 2024
Raja Tamil
Firebase Javascript

The onAuthStateChanged() 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() → you’re here
  3. signInWithEmailAndPassword()
  4. signOut()

The onAuthStateChanged() method gets triggered when a user authentication state changes such as creating a new user account, logging in to a user account, or logging out.

For example, when the app loads for the first time the onAuthStateChange() method will return null because at that time no user account is created.

As soon as a new user account is created, the onAuthStateChanged() method will return the newly logged-in user’s data.

Before going any further, I assume that you already know how to create a Firebase project as well as how to add the Firebase SDK to your web app.

1. Import Firebase Authentication SDK Library

The first step is to Import the Firebase Authentication SDK library via either NPM or CDN (I use CDN in the below example) and destructure the getAuth() and onAuthStateChanged() methods.

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

2. Create An Instance Of Authentication Object

The second step is to create an instance of an authentication object that is needed for using any Firebase Authentication SDK methods.

const auth = getAuth();

3. Call onAuthStateChanged() Method

The third step is to call the onAuthStateChanged() method on the page load.

onAuthStateChanged(auth, (user) => {
  console.log(user);
});

The onAuthStateChanged takes two arguments.

The first one is the authentication object auth that I’ve already created above,

The second argument is the callback anonymous function with the parameter user which is a JavaScript object that holds the logged-in user data.

This anonymous callback function will be triggered anytime the user authentication state changes.

If the user is logged in, the callback function will be triggered and we can access the logged-in user data from the parameter user object.

4. Check If The User Is Logged In Or Not

Let’s check if the user is logged in or not by checking the value of the parameter user of the onAuthStateChanged() method callback function.

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

const auth = getAuth();

onAuthStateChanged(auth, (user) => {
  if(user) {
    console.log("user is logged in");
    console.log(user); // user object
  } else {
    console.log("user is not logged in");
    console.log(user); // null
  }
});