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:
// axios.ts
import { useAuth0 } from "@auth0/auth0-react";
import axios from "axios";
const fetchClient = axios.create();
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);
}
);
export default fetchClient;
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