Search code examples
reactjsaxiosauth0

Using Auth0 React Hook on all Axios requests


I have set up Auth0 with React by following their Quickstart tutorial.
Basically my React app is wrapped around their Context Provider and I have access to the useAuth0 hook in any of my components.

This is how I would make a request to my API:

const TestComponent = () => {
  const { getTokenSilently } = useAuth0();

  const getObjectsFromAPI = async () => {
    const token = await getTokenSilently();
    const axiosConfig = {
      headers: {
        Authorization: "Bearer " + token
      }
    };

    const response = await axios.get(
      "/api/objects/",
      axiosConfig
    );

    // ... do something with the response

  };

  return ... removed code for brevity
};

Is there a way to make the requests without having to write the token and axiosConfig on each request?

I know that I can initialize a new axios instance with a config, but I cannot use the useAuth0 hook outside the Context Provider.


Solution

  • but I cannot use the useAuth0 hook outside the Context Provider.

    Right, not sure how you can avoid token generation per request but you can save the axios config part by passing the token to a shared axios instance, something like:

    http.js

    const instance = axios.create({
      // your config
    });
    
    export const authorized = (token) => {
       instance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
       return instance;
    }
    

    And in your component:

    import http from '/path/to/above/http.js';
    
    const TestComponent = () => {
      const { getTokenSilently } = useAuth0();
    
      const getObjectsFromAPI = async () => {
        const token = await getTokenSilently();
    
        const response = await http
           .authorized(token)
           .get('/api/objects/');
    
        // ...
      };
    };