How can I request a new access token after the existing token expires with the firebase refresh token?

Viewed 570

I have a react app and I am using firebase auth for authentication. I have an auth context and everything works great. The issue is after 1 hour, the token expires and since we are using our auth token for api authentication the apis fail to work after one hour. How can I monitor when the token expires, and request a new one using the refresh token that is in firebase?

 useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      if (user) {
        const lastSignInTime = new Date(user.metadata.lastSignInTime);
        const lastSignInTimeTimeStamp = Math.round(lastSignInTime.getTime() / 1000);
        const yesterdayTimeStamp = Math.round(new Date().getTime() / 1000) - 24 * 3600;

        if (lastSignInTimeTimeStamp < yesterdayTimeStamp) {
          logout();
          setCurrentUser({
            ...currentUser,
            user: null,
            isVerified: false,
            email: '',
            accessToken: '',
          });
          return false;
        }
      }
      setCurrentUser({
        ...currentUser,
        user: user || null,
        isVerified: user ? user.emailVerified : false,
        email: user ? user.email : '',
        accessToken: user ? user.Aa : '',
      });
      setLoading(false);
    });
    return unsubscribe;
  }, []);
1 Answers
Related