Firebase getToken () TypeError: Cannot read property

I am trying to get the token of my user of my site signed today. However, javascript cannot get the value to me. I think there are two problems here:

  • When I start Auth.currentUser at startup, I get this error “TypeError: Can't read the getToken property“ null. ”But when I type Auth.currentUser.getToken () in the console, the object with the token actually appears.

  • What getToken () returns to me is a promise object with its key "ea" containing the value of the token. but when I do Auth.currentUser.getToken (). ea, he gets me "null". How can I get a token directly from an object?

Thanks!

My token extraction code:

var Auth = firebase.auth() var token = Auth.currentUser.getToken() 

This screenshot may be useful: Chrome console result

+5
source share
2 answers

According to the documentation of firebase.User:getIdToken() :

Returns the JWT token used to identify the user to the Firebase service.

Returns the current token, if it has not expired, otherwise it will update the token and return a new one.

The method returns a promise, as it may require a return pass to the Firebase servers if the token expired:

 Auth.currentUser.getIdToken().then(data => console.log(data)) 

Or in more classic JavaScript:

 Auth.currentUser.getIdToken().then(function(data) { console.log(data) }); 

Log output:

eu ... Bipa

Refresh . To verify that the user has been signed before receiving the token, run the above code in the onAuthStateChanged listener :

 firebase.auth().onAuthStateChanged(function(user) { if (user) { user.getIdToken().then(function(data) { console.log(data) }); } }); 
+14
source

Here is an example of how to get id id using NodeJS

 var firebase = require('firebase') firebase.initializeApp({ apiKey:********* databaseURL:********* }) var customToken = ********* firebase.auth().signInWithCustomToken(customToken).catch(function(error) { var errorMessage = error.message console.log(errorMessage) }) firebase.auth().onAuthStateChanged(function(user) { if (user) { firebase.auth().currentUser.getToken().then(data => console.log(data)) } else { console.log('onAuthStateChanged else') } }) 
+1
source

All Articles