Mutlu.dev

How Axios Processes Interceptors: Order Matters

If you’ve written any frontend app with authentication, you've probably used Axios interceptors. But have you ever thought about the order in which they run? I hadn’t, until I ran into a bug (or maybe a feature).

While setting up my refresh token logic, I created two request interceptors like this:

instance.interceptors.request.use(refreshTokenInterceptor);
instance.interceptors.request.use(authenticationTokenInterceptor);

refreshTokenInterceptor checks if the token is expired and, if it is, fetches a new one from the server and saves it to localStorage.

authenticationTokenInterceptor then takes the token from localStorage and attaches it to the request.

Well, when I tested it, the token was getting refreshed, but the request was still being sent with the old token. After a few console.logs, I figured out the issue: request interceptors run in reverse order to how they’re defined.

After a quick Google search, I found this is a known behavior in Axios:

Axios states that request interceptors are stack-based; they run like popping from a stack.

I'm still not sure if this is a bug or a feature, but it doesn’t look like it’ll change anytime soon. So next time you add more than one interceptor, keep this in mind.

#axios #fyi