'After refresh, firebase Auth current user returns null
Here is my code on profile page, this works fine first time when i redirect from login method of AuthService
const user = firebase.auth().currentUser;
if (user != null) {
this.name = user.displayName;
this.uid = user.uid;
} else {
this.name = "Unknown";
}
However, if I refresh the page or go to any other page and come back to this profile page, currentUser becomes null.
Here is my auth service code.
import * as firebase from "firebase/app";
import { auth } from "firebase/app";
async googleSignin() {
firebase
.auth()
.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(async () => {
const provider = new auth.GoogleAuthProvider();
const credential = await this.afAuth.auth.signInWithPopup(provider);
this.updateUserData(credential.user);
this.router.navigate(["/profile"]);
return;
});
}
Why i am loosing the currentUser? I even added Persistence.LOCAL too.
Solution 1:[1]
When you navigate to a new page, you're reloading the Firebase Authentication SDK. At this point Firebase automatically refreshes the authentication state of the current user, but this may require a roundtrip to the server. And by the time your `firebase.auth().currentUser runs that refresh apparently isn't done yet.
For this reason you should use onAuthStateChange
to listen for changes, as shown in the documentation on getting the currently signed in user:
firebase.auth().onAuthStateChanged(function(user) {
if (user != null) {
this.name = user.displayName;
this.uid = user.uid;
} else {
this.name = "Unknown";
}
});
Solution 2:[2]
You can also save the user data to local/session storage in case the service/guard does not recieve it in time because of the async operation.
Solution 3:[3]
The default persistence strategy is IndexedDB. However, that strategy will not work for me – at least on localhost:3000
.
Changing the strategy to use local storage fixed it:
import { initializeAuth, browserLocalPersistence } from 'firebase/auth';
const auth = initializeAuth(app, {
persistence: browserLocalPersistence
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Gerg? Éles |
Solution 3 | AndrewHenderson |