skip to Main Content

Is there any built-in caching of onAuthStateChanged?
I’m building an app using Next.js and Axios.
I defined this method:

import { auth, provider } from "./firebase-client";
import { signInWithPopup, onAuthStateChanged } from "firebase/auth";
export function getCurrentUser() {
  return new Promise((resolve, reject) => {
    const unsubscribe = onAuthStateChanged(
      auth,
      (user) => {
        unsubscribe();
        resolve(user);
      },
      reject
    );
  });
}

And I want to pass an authorization header on some requests, so what I did for every route is:

export async function get(route) {
  try {
    const currentUser = await getCurrentUser();
    let response;
    if (currentUser) {
      response = await axios.get(route, {
        headers: { Authorization: `Bearer ${currentUser.accessToken}` },
      });
    } else {
      response = await axios.get(route);
    }

    return response;
  } catch (error) {
    console.log(error);
    return { error: error.response.data };
  }
}

This calls onAuthStateChanged on every request to fill in the header. Is this a bad practice? How do I make it better?

2

Answers


  1. The approach looks about right. The Firebase SDK already caches the ID token (that is what user is based on) in local storage, so subsequent calls should take much more time than it takes to decode that token.

    Login or Signup to reply.
  2. Why are you using onAuthStateChanged to get the current user synchronously? That doesn’t make any sense. That observer method is only for monitoring changes in the user auth state as they happen, allowing your app to globally and immediately respond to auth changes. It’s not for one-time use.

    If you want to know at any given moment if the user is signed in, use auth.currentUser instead as shown in the documentation, using the second example and not the first one.

    You can also get the currently signed-in user by using the currentUser property. If a user isn’t signed in, currentUser is null:

    import { getAuth } from "firebase/auth";
    
    const auth = getAuth();
    const user = auth.currentUser;
    
    if (user) {
      // User is signed in, see docs for a list of available properties
      // https://firebase.google.com/docs/reference/js/auth.user
      // ...
    } else {
      // No user is signed in.
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search