0

I have a web application using html-js-css and a flask server. My web app is a multi-pages app which apparently means that I have to Initialize firebase for each page in which i want to use it -.-

The problem is that every time I initialize firebase app, I lose the current user so while in my main page, after log-in, if I write:

const USER = firebase.auth().currentUser;
console.log(USER.uid);

I get my user ID, as soon as I move to another page and repeat the above code, I get the error:

TypeError: USER is null

Is there a way to either:

  • avoid Initializing the firebase-app at avery page
  • keep the CurrentUser (even storing it securely somewhere)

Thank you

Workaround:

I got this workaround working before Frank answer which is probably the best way to proceed. Instead I just stored the user id in an encrypted variable accessible to all pages.

Since the main.html page is always loaded, I store/removed the variable in a onAuthStateChanged listener there so as soon as the user is logged out, that variable is removed:

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        cached_uid = JSON.stringify(user.uid);
        cached_uid = btoa(cached_uid);
        localStorage.setItem('_uid',cached_uid);
    } else {
        localStorage.removeItem('_uid');
    }
});

then on the other pages:

function loadUID(){
        var uid = localStorage.getItem('_uid');
        if (!uid) return false;
        uid = atob(uid);
        uid = JSON.parse(uid);
        return uid
      }

I followed this to find this solution: How to send variables from one file to another in Javascript?

Fabio Magarelli
  • 1,031
  • 4
  • 14
  • 47

1 Answers1

1

You will need to initialize the Firebase app on each page, but that is supposed to be a fairly cheap operation.

To pick up the user on the new page, Firebase runs a check against the server to ensure the user token is still valid. Since this code calls a server, its result likely isn't available yet when your firebase.auth().currentUser runs.

To solve this, run the code that requires a user in a so-called auth state change listener:

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

Also see the Firebase documentation on getting the currently signed in user.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you Frank, I actually found a workaround which was to store the UID in an encrypted variable. see my question edit. – Fabio Magarelli Feb 27 '20 at 09:35
  • 1
    Great to hear! Two things: 1) there's no need to encrypt the UID, as it's not a secret. See https://stackoverflow.com/q/37221760, 2) please post your workaround as an answer, instead of in the question.Posting self-answers is acceptable and even encouraged on Stack Overflow. – Frank van Puffelen Feb 27 '20 at 13:56