0
0
FirebaseHow-ToBeginner · 3 min read

How to Use onAuthStateChanged in Firebase for Auth State Tracking

Use onAuthStateChanged from Firebase Auth to listen for changes in the user's sign-in state. It runs a callback whenever the user signs in or out, letting your app respond immediately to authentication changes.
📐

Syntax

The onAuthStateChanged function takes two main parts: the Firebase Auth instance and a callback function. The callback receives the current user object or null if signed out.

  • auth: Your Firebase Auth instance.
  • callback: Function called with the user state.
  • unsubscribe: The function returned to stop listening.
javascript
const unsubscribe = onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in
  } else {
    // User is signed out
  }
});
💻

Example

This example shows how to use onAuthStateChanged to detect when a user signs in or out and log their status to the console.

javascript
import { initializeApp } from 'firebase/app';
import { getAuth, onAuthStateChanged } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID'
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

const unsubscribe = onAuthStateChanged(auth, (user) => {
  if (user) {
    console.log('User signed in:', user.email);
  } else {
    console.log('User signed out');
  }
});

// Later, to stop listening:
// unsubscribe();
Output
User signed out // or User signed in: user@example.com
⚠️

Common Pitfalls

  • Not unsubscribing: Forgetting to call the unsubscribe function can cause memory leaks.
  • Assuming user is always non-null: The callback runs with null when signed out, so always check.
  • Using onAuthStateChanged before initializing Firebase Auth causes errors.
javascript
/* Wrong: Not checking for null user */
onAuthStateChanged(auth, (user) => {
  console.log(user.email); // Error if user is null
});

/* Right: Check user before accessing properties */
onAuthStateChanged(auth, (user) => {
  if (user) {
    console.log(user.email);
  } else {
    console.log('No user signed in');
  }
});
📊

Quick Reference

onAuthStateChanged Cheat Sheet:

TermDescription
authFirebase Auth instance from getAuth()
callback(user)Function called on auth state change with user or null
unsubscribeFunction returned to stop listening
userUser object when signed in, null when signed out

Key Takeaways

Use onAuthStateChanged to react instantly to user sign-in or sign-out events.
Always check if the user object is null before accessing its properties.
Call the unsubscribe function when you no longer need to listen to avoid memory leaks.
Initialize Firebase Auth before using onAuthStateChanged to prevent errors.