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
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.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.