I am learning Firebase and I am using the latest version 9.4.1 for Web with Javascript and Jquery. I have the following code where I check if the user is currently logged in and if yes then he is not allowed to access the login page. Similarly, if the user is logged in then I also hide the "Sign Up" and "Sign In" buttons and display the "Sign Out" button. However, during my experiment I found out that these actions are performed quite slowly. This means that if I try to access the login page then the page loads for nearly half a second, displays all the contents of the page (login form and stuffs) in a flash for half a second and then decides to redirect back to the index page. Even the "Sign Up" and "Sign In" buttons are displayed for the similar amount of time before getting hidden and "Sign Out" button takes time to display too. Why these delays are there? Is there any way I can eliminate these delays and make the actions be performed instantly?
Authentication checking code
onAuthStateChanged(auth, (user) => {
if(user){
const uid = user.uid;
(window.location.pathname.split("/").pop() == 'login.php')?location.replace("index.php"):null;
$(".logout").show();
$(".login").hide();
$(".register").hide();
}
});
CodePudding user response:
When the page loads Firebase tries to restore the user's authentication state from the information it has in local storage. This requires that it makes a call to server to check the credentials, and things like whether the account is disabled. This call takes some time, and only once the call completes will your onAuthStateChanged
be called with the result.
This means that the short flash you see is quite normal, and can not be prevented with just the Firebase API. A trick you can do is store a small token value in local storage yourself, and then reading that right as the page loads to determine whether the user is likely to be authenticated. Michael Bleigh explained this technique in his Google I/O talk Architecting Mobile Web Apps
While you cannot prevent the flash in all cases with this, you can use it to prevent the flash for most users effectively.