Eugene Mala Eugene Mala - 6 months ago 144
Javascript Question

Firebase: Store anonymous authentication in cookies

I am developing multi page application, that uses firebase as a back-end.
On every page after firebase initialization I have the following code:

firebase.auth().signInAnonymously().catch(...);

firebase.auth().onAuthStateChanged(function(user)
{
if (user) {
// ...
} else {
// User is signed out.
// ...
}
// ...
});


which sign in every visitor anonymously.

The problem is, when user navigates to another page of my application or opens it in a new tab, or just refreshes the current page - new anonymous user is generated.

I can use client side cookies to store anonymous user id, but how can I later (after page refresh) use that stored anonymous user id, to sign in user with that id?

Answer

It was my mistake, firebase store anonymous user authorization in local storage by default.

My code sample should be rewritten this way to work properly:

firebase.auth().onAuthStateChanged(function(user) 
{
    if (user) {
        // User is signed in
        // ...
    } else {
        // User is signed out.
        firebase.auth().signInAnonymously().catch(/*...*/);
    }
    // ...
});