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: