On the way to success
On the way to success

Reputation: 210

How can you persist a logged-in user with firebase?

Thanks a bunch for reading this newbie's question.

So, there is a ReactJS app which is using firebase for its authentication.

Everytime the page is refreshed, the user is gone forever until you login in with the redirected login page.

What have been done so far?

Well, after plodding through all the possible Stackoverflows flowing flawless answers, following have been done:

  1. Implemented the onAuthStateChanged() function like as it appears below:

  firebase.auth().onAuthStateChanged((user) => {
            if (user) {
                console.log('user is logged in');
            } else {
                console.log('user is logged out now')
            }
        });

  1. Set the persistence, which seems to be a silent worker, as follows:

 firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE)
        .then(function () {
          console.log("successfully set the persistence");
    
        })
        .catch(function (error) {
          console.log("failed to ser persistence: " + error.message)
        });

Every page reloads logs the user out just like that. Gone!. Nothing. Not even a trace of its dust!

To have a better understanding of this crippling code, I can give you the following screenshots of the console messages.

You get this when you logged in

enter image description here

And the following when the page is refreshed.

Why do you think this error pops up even after applying the above?

Thanks again!

Update1: Took down the setPersistence thing. And it turns out that the user is logged in even after page reloads to the login.

Update 2: User is actually get pulled out when refreshing the page. Now that's what we need to solve here. What do you guys think?

enter image description here

Upvotes: 1

Views: 1007

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317322

The Firebase Auth SDK enables persistence by default. If you want that default behavior, don't call firebase.auth().setPersistence() at all. Just use onAuthStateChanged to know when the persisted user object is first available.

Upvotes: 1

Related Questions