Reputation: 761
I was wondering how to persist the authentication state with firebase. What I am doing is trying to set the persistence state and I do it like this:
login.addEventListener('click', function (e) {
e.preventDefault();
var email = emailInput.value;
var password = passwordInput.value;
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(function() {
auth.signInWithEmailAndPassword(email, password)
.then(function (user) {
})
.catch(function (error) {
alert(error);
});
})
});
The problem is that when I refresh my web app the session appears not to be persisted. It redirects the user back to the login screen which is not the desired out put at all. The desired output would the session for the user is saved and the user is able to go through the app without having the issue being forced to login again.
I am following the firebase documentation:
https://firebase.google.com/docs/auth/web/auth-state-persistence
Upvotes: 3
Views: 2674
Reputation: 317392
If you want to know if a user was previously signed in to your site when a new page loads, you should use an auth state observer to receive a callback that notifies you when a user is first known to be signed in. It does not trigger immediately when the page loads - it will take some time for the SDK to load the user account and determine if it's valid.
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
Don't use firebase.auth().currentUser
to determine if the user was previously signed in. It will initially always be null when the page loads. For more information, read this blog.
Upvotes: 3