CSFrequency / react-firebase-hooks

React Hooks for Firebase.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

What's the suggestion for token refresh?

RobTS opened this issue · comments

commented

For a while, I have been wondering why my token is not refreshed automatically, despite using useIdToken. I come back to my machine after a break or the next morning, and get Auth issues.

So I did some research today and it seems (according to this docs update) that Firebase does in fact not handle it for us.

I can't seem to find a best practice suggestions in the docs of this hooks library, but believe an auto-refresh hook based on a timeout would be a great extension.

Edit: Something like that would do the trick, but uses non-public attributes:

  const [user, loading, authError] = useIdToken(firebaseWrapper.auth);
  const token = (user as { accessToken: string } | null)?.accessToken;

  useEffect(() => {
    if (!user || !token) return;
    const expiresIn = Interval.fromDateTimes(
      new Date(),
      new Date((user as any).stsTokenManager.expirationTime),
    );
    const timer = setTimeout(() => {
      user.getIdToken(true).catch(console.error);
    }, Math.max(expiresIn.length('milliseconds') - 60000, 0));
    return () => clearTimeout(timer);
  }, [user, token]);

I am also facing with similar issues, so I am working on a Expo RN Mobile App, where I have Email auth using Firebase, it successfully, logs in and creates the user, but when I reload the app, the auth state is not logged in...