Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 404
Dev Catalin Avatar asked Jul 31 '26 08:07

Dev Catalin


1 Answers

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/');

    // ...
  };
};
like image 175
Daniel Avatar answered Aug 03 '26 08:08

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!