Why access token cannot be provided with user from the useAuth0 hook

Hi, I’ve been wondering for some time about reasoning of having getAccessTokenSilently as a async call instead of returning the token the same way the user is returned. I understand it could be an async call if token is not in the cache or requires refreshing, but could the initial one also be returned similar to how the { user } is returned?

I mean, if { user } obtained from useAuth0() is not null, then we’re sure that he has a not expired access token in this moment which could be provided in the same way { user } is provided like { accessToken, user } = useAuth0().

Of course, access token can become expired after some time, but the same could be told for the user which becomes not actual in { accessToken, user } = useAuth0().

Could you tell me about the reasoning behind that and/or a way to achieve that writing my own custom hook which would also return the initial accessToken after logging?

For posterity: seems this implementation works, note that the user needs to be logged in to call getAccessTokenSilently, otherwise you get an error.

export function useAuth() {
  const auth0 = useAuth0();
  const [accessToken, setAccessToken] = useState<string | null>(null);
  useEffect(() => {
    (async () => {
      const token = await auth0.getAccessTokenSilently();
      setAccessToken(token);
    })();
  }, [auth0]);
  return { ...auth0, accessToken };
}

The question for the reasoning still stands if anyone could answer.

1 Like