access token from auth0provider outside of react components

I was having a similar issue on how to use getAccessTokenSilently outside of a React component, what I ended up with was this:

My HTTP client wrapper

export class HttpClient {
  constructor() {
    HttpClient.instance = axios.create({ baseURL: process.env.API_BASE_URL });

    HttpClient.instance.interceptors.request.use(
      async config => {
        const token = await this.getToken();

        return {
          ...config,
          headers: { ...config.headers, Authorization: `Bearer ${token}` },
        };
      },
      error => {
        Promise.reject(error);
      },
    );

    return this;
  }

  setTokenGenerator(tokenGenerator) {
    this.tokenGenerator = tokenGenerator;
    return this;
  }

  getToken() {
    return this.tokenGenerator();
  }
}


On my App root, I pass the getAccessTokenSilently from auth0

 useEffect(() => {
    httpClient.setTokenGenerator(getAccessTokenSilently);
  }, [getAccessTokenSilently]);

And that's it!

You now have an axios instance ready to do authenticated requests with


This is a variant of the answer by @james-quick, where I am using a "RequestFactory" to generate requests in the axios format, and then just adding the auth header from Auth0

I was facing the same issue, and I got around this limitation by moving all my API call logic into a custom hook that I created:

import { useAuth0 } from '@auth0/auth0-react';
import { useCallback } from 'react';
import makeRequest from './axios';

export const useRequest = () => {
  const { getAccessTokenSilently } = useAuth0();

  // memoized the function, as otherwise if the hook is used inside a useEffect, it will lead to an infinite loop
  const memoizedFn = useCallback(
    async (request) => {
      const accessToken = await getAccessTokenSilently({ audience: AUDIANCE })
      return makeRequest({
        ...request,
        headers: {
          ...request.headers,
          // Add the Authorization header to the existing headers
          Authorization: `Bearer ${accessToken}`,
        },
      });
    },
    [isAuthenticated, getAccessTokenSilently]
  );
  return {
    requestMaker: memoizedFn,
  };
};

export default useRequest;

Usage Example:

 import { RequestFactory } from 'api/requestFactory';

 const MyAwesomeComponent = () => {
   const { requestMaker } = useRequest(); // Custom Hook
   ...
   requestMaker(QueueRequestFactory.create(queueName))
     .then((response) => {
       // Handle response here
       ...
     });
 }

RequestFactory defines and generates the request payload for my different API calls, for example:

export const create = (queueName) => ({ method: 'post', url: '/queue', data: { queueName } });

Here is a full Auth0 integration PR for reference.