How to get token from outside React components?

I am using axios to make requests to my APIs. Currently I use an axios interceptor to set the token to every request that gets sent (so I don’t have to repeat getting the token from within the component). Is there any way to do this? My first attempt looks something like this:

fetchClient.interceptors.request.use(
  async (config) => {
    const { user, getAccessTokenSilently } = useAuth0();

    if (!user || !user.sub) return Promise.reject("No user");

    const token = await getAccessTokenSilently({
      audience: process.env.REACT_APP_AUTH0_API_AUDIENCE,
    });

    const userId = user.sub.split("|")[1];
    config.headers["Authorization"] = `Bearer ${token}`;
    config.headers["userId"] = userId;
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

But of course you can’t call Hooks and therefore can’t call getAccessTokenSilently from non functional components. Any way to get around this? Thanks all

Hi, I’m facing the same issue, I want to get the access token outside a React Component.
Did you find a solution? :slight_smile:

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

This did not work for me: when intercept is called, this is not defined.

Anyone managed to make it work?

Had the same issue, you need to bind the functions:

class AuthInterceptor {
  private getToken: any = undefined;

  constructor() {
    this.intercept = this.intercept.bind(this);
    this.setAuthGetter = this.setAuthGetter.bind(this);
  }
...