Home > Software design >  Best practice to get user's idToken from Firebase - using getIdToken(/* forceRefresh */ true) l
Best practice to get user's idToken from Firebase - using getIdToken(/* forceRefresh */ true) l

Time:11-08

I'm working on a dashboard website in react.js where the users can analyze multiple different charts. To get the data for the charts from my node.js server I need to get the user's ID token to be able to verify it on the server side (return data only if user is authorized).

In the firebase documentation it is shown how to get the current id token:

firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
  // Send token to your backend via HTTPS
  // ...
}).catch(function(error) {
  // Handle error
});

In my case, this leads to a Firebase: Error (auth/quota-exceeded) in case the user switches between different charts too frequently or refreshed the page too often.

When I don't follow the documentation and do not use /* forceRefresh */ true the error disappears but it might happen that the idToken is expired. Do I always force the idToken to refresh for each API call like shown in the documentation? If not: How where and when do I check if the token is already expired? What is the best practice to handle this?

Thanks!

CodePudding user response:

As explained in the doc, in your case you don't need to pass /* forceRefresh */ true:

getIdToken returns the current token if it has not expired. Otherwise, this will refresh the token and return a new one.

https://firebase.google.com/docs/reference/js/v8/firebase.User#getidtoken

  • Related