alan2207 / bulletproof-react

🛡️ ⚛️ A simple, scalable, and powerful architecture for building production ready React applications.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: axios in React lifecycle

s1gr1d opened this issue · comments

I love your project and have been using it for a while to look for examples. I've just been wondering how the axios instance and interceptors work with React in the way they are implemented now.

I suppose the instance is created once you reload the page and then it gets the token from the store. But what if there is no token at that time? What happens when the token changes during usage of the application? I implemented the axios instance according to bulletproof-react in one of my projects and have the issue that the axios instance is not refreshed after the user logs in (token change).

How does the example work here? Or do we need to put the axios instance in a React hook which can change the values?

Thanks in advance for some clarity 🙏

Maybe putting axios and the interceptors in a React context? Like it is done in this article?

Here are also some suggestions: axios/axios#2315

Hey @s1gr1d ,

I am curious, why do you need React to track your tokens?

If the token needs to be refreshed, that should be done in the background without involving React in the process. For that, you can try https://github.com/Flyrell/axios-auth-refresh which allows refreshing tokens within interceptors.

@alan2207 what about auth0 where you have a hook called useAuth0 which exposes a function getTokenSilently which is async 🤔

So in that case I need axios to be inside the react context to being able to inject the token into an interceptor.

In our case we use something like this:

export const ApiClientProvider: FC<PropsWithChildren> = ({ children }) => {
  const { getAccessTokenSilently } = useAuth0();
  const { API_URL } = useEnvContext();

  const value = useMemo(() => {
    const instance = axios.create({
      baseURL: API_URL,
    });

    instance.interceptors.request.use(async (config) => {
      const token = await getAccessTokenSilently();
      config.headers = {
        ...config.headers,
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      };
      return config;
    });

    return { apiClient: instance };
  }, [getAccessTokenSilently, API_URL]);

  return <ApiClientContext.Provider value={value}>{children}</ApiClientContext.Provider>;
};

Well it depends on how you get token and store in the browser.
Usually we get token from POST login request.
So I don't think we have to take care of token is changed. maybe user is changed or user manipulates token value on purpose.
We can navigate back to login page and make user re-login again I reckon.