How to use the getIdToken() auth method in firebase version 9?
It works like this below in version 8
import firebase from "firebase";
const token = await firebase.auth().currentUser.getIdToken(/* forceRefresh */ false);
I tried this in version 9 but it is not working
import { getIdToken } from "firebase/auth";
const token = await getIdToken(/* forceRefresh */ false);
I also tried this below and it is not working
import { getAuth } from "firebase/auth";
const auth = getAuth();
const { currentUser } = auth;
const token = await currentUser.getIdToken(/* forceRefresh */ false);
The getIdToken() function takes User as parameter and not the refreshToken boolean as in name-spaced SDK.
import { getIdToken, onAuthStateChanged } from "firebase/auth";
onAuthStateChanged(auth, async (user) => {
if (user) {
const token = await getIdToken(user);
}
});
As far as the error goes, getAuth() returns auth instance but user's auth state might now have loaded yet. Try running the same in onAuthStateChanged or adding a null check as suggested by @Frank.
Looks like getIdToken() function takes two arguments in the latest version (9.6.6): user and a boolean. So, this is the working code in my case:
import { getAuth, getIdToken } from "firebase/auth"
const auth = getAuth()
const { currentUser } = auth
const token = await getIdToken(currentUser, true)