I am building a small site using plain HTML and javascript, and I am using Firebase for authentication. When users go to a certain page, I would like to redirect them to another page if they are signed in. This is the code I am using to achieve that (all scripts are placed in the <head>
):
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-auth.js"></script>
<script>
const firebaseConfig = {
// ...
};
firebase.initializeApp(firebaseConfig);
firebase.auth().onAuthStateChanged((user) => {
window.location.href = "/feed";
});
</script>
This redirects the user properly, but the user briefly sees the page meant for non-authenticated users during the time it takes for Firebase to fetch the auth state and for the onAuthStateChanged
callback to be fired. Is there a way I can prevent rendering of the HTML page until onAuthStateChanged is called?
CodePudding user response:
have you tried async/await?
Once an Html file is rendered from top to bottom and you are not using the async/await method, html will keep rendering once it's an asynchronous function.
I would recommend you to try it like this to obligate the render wait for the auth response:
<script>
const firebaseConfig = {
// ...
};
firebase.initializeApp(firebaseConfig);
async function firebaseAuth(){
try{
const authResponse = await firebase.auth().onAuthStateChanged((user) => {
window.location.href = "/feed";
});
}catch(e){
console.log(e);
}
};
firebaseAuth();
</script>
You can read more on doc: https://www.w3schools.com/js/js_async.asp
CodePudding user response:
Firebase automatically restores the user when the page loads. This requires a call to the server however, amongst others to check if the account was disabled, so it may take some time.
The common workaround is to store your own value in local storage that indicates whether you think the user is likely to be signed in, and (if so) redirect to the authenticated page right away.
If/when the user ever gets signed in, you'd have an auth state listener in that page to to redirect them back, so most users will see the happy path in that case.
Firebaser Michael Bleigh covered this in a talk at Google I/O here.