Search code examples
javascriptreactjsfirebasefirebase-authentication

Most ideal way to call firebase getIdToken


i am implementing user authentication with the help of firebase in my React project. So, I am confused over something.

I am verifying the user from firebase and then getting a token on frontend which is sent to backend via headers and verfied there once.

I read the docs and came to know that firebase token gets expired after 1 hr by default so we have to use "getIdToken" like

 firebase.auth().onAuthStateChanged(async user => {
      if (user) {
        console.log(user, 'user123 inside firebaseAuth')
        const token = await user.getIdToken()

        Cookies.set('my_token', token, { domain: domain })
      }
    })

but how do i manage this function , do i have to call it everytime the component updates or everytime before hitting api or first time the component renders ?

The thing is i do not want this token to get expire until the user logs out himself / herself even if he is in a different component and sitting ideal for too long.


Solution

  • You can get the Firebase ID Token every time you are making an API call to your server:

    async function callAPI() {
      const user = firebase.auth().currentUser
      if (user) {
        const token = await user.getIdToken()
        const res = await fetch("url", {
          headers: {authorization: `Bearer ${token}`}
        })
      } else {
        console.log("No user is logged in")
      }
    }
    

    You could get the ID token once when the component mounts but then you'll have to deal with onIdTokenChanged to keep it updated in your state. Using the method above you'll get a valid token always.