How to get token from outside React components?

Create a Interceptor class, init and export a instance

class AuthInterceptor {
  setAuthGetter(getToken) {
    this.getToken = getToken;
  }

  async intercept(config) {
    if (!this.getToken) {
      return config;
    }

    try {
      const token = await this.getToken();
      config.headers['Authorization'] = `Bearer ${token}`;
    } catch (e) {
      console.log(e);
    }
    return config;
  }
}

export const authInterceptor = new AuthInterceptor()
fetchClient.interceptors.request.use(authInterceptor.intercept)

Create a function component to set the getToken method

function AuthInject() {
  const { user, getAccessTokenSilently } = useAuth0();

  useEffect(() => {
    authInterceptor.setAuthGetter(getAccessTokenSilently);
    return () => authInterceptor.setAuthGetter(undefined);
  }, [getAccessTokenSilently]);

  return null;
}

//set AuthInject as children
<Auth0Provider {...auth0Config}>
  <AuthInject />
  <App />
</Auth0Provider>;
3 Likes