VueJS + Firebase Authentication Can't Access Session Before Scripts Load
So i'm working on a project and i'm struggling a bit... I'm using VueJS for the frontend and Firebase Authentication to log users in.
I'm trying to determine whether a user is currently logged in or not using firebase.auth().currentUser;
(If returns null then no user is logged In) Sounds simple right!?
I'm running the currentUser() in my vueJS created()
function. However, running firebase.auth().currentUser;
here seems to always return null. But however, if i use a set timeout method then it is able to fetch the users data. It looks to me like vue is trying to fetch the data before it has loaded in.
I hope this isn't too hard to understand - i'm quite new to Vue and firebase! Please find snippets of my code attached below.
Vue.config.devtools = true;
var app = new Vue({
el: '#app',
data: {
user: '',
loggedIn: false
},
created() {
var user = firebase.auth().currentUser;
if (user != null){
this.user = user;
this.loggedIn = true;
} else {
this.loggedIn = false;
}
}
})
Below are the firebase scripts i'm loading at the bottom of the page body
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-analytics.js"></script>
<script src="js/firebaseConfig.js" type="text/javascript"></script>
Essentially, how can i fix this without using a setTimeout()
method? and also how does firebase get this session, which script handles this?
Solution 1:
firebase.auth().currentUser
always returns null when the page is first loaded. It will only contain an actual user object after the SDK has determined that the user is actually signed in. There is no guarantee exactly how long that will take.
The preferred way to find out when that happens is to use an auth state observer, as shown in the documentation.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
// ...
} else {
// User is signed out.
// ...
}
});
You can use this callback to determine when it's time to render content for that individual user.
I suggest also reading more about the behavior of the Firebase Auth SDK in this blog.