0
votes

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

1
"when I refresh my web app the session appears not to be persisted" How did you determine that? None of your code currently deals with a restored authentication state. To do so, use an auth state listener as shown in the first example here: firebase.google.com/docs/auth/web/…Frank van Puffelen
Also check whether it is necessary to explicitly set the persistence. On most environments it will be set correctly by default.Frank van Puffelen
Try making firebase.auth.Auth.Persistence.SESSIONMeghshyam Sonar

1 Answers

1
votes

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.