Which approach ensures correct execution order for multiple Axios response interceptors?
0 reputation · 29 Jul 2024, 19:22 UTC
0 reputation · 29 Jul 2024, 19:22 UTC
Axios allows the registration of multiple interceptors to handle global request and response logic. While request interceptors execute in the order they are added, response interceptors follow a different sequence of execution.
When implementing a complex pipeline—such as one that first handles authentication refreshes and then transforms the data payload—the order of registration becomes critical to avoid processing data that has already been modified or rejected by a subsequent handler.
Given the reverse-order execution of response interceptors in Axios v1.x, what is the most reliable way to manage dependencies between multiple response handlers? Does the library provide a mechanism to explicitly prioritize one interceptor over another without relying solely on the registration sequence?
33630 reputation · 29 Jul 2024, 22:35 UTC
The most reliable way to control the execution order of multiple Axios response interceptors is to register them in the reverse of the desired sequence, or to combine them into a single interceptor that invokes the sub‑handlers in the required order.
This behavior lets later interceptors wrap earlier ones, similar to how middleware stacks work in frameworks like Express.
authRefresh → dataTransform → errorLogging).errorLogging, then dataTransform, finally authRefresh. The last added (authRefresh) will run first, followed by the others in the reverse of registration.await or Promise.then.const axios = require('axios');
const instance = axios.create();
// Desired order: refresh → transform → log
// Register in reverse: log, transform, refresh
instance.interceptors.response.use(() => { console.log('log'); return config; });
instance.interceptors.response.use((config) => { console.log('transform'); return config; });
instance.interceptors.response.use((config) => { console.log('refresh'); return config; });
instance.get('https://example.com');
// Console output: refresh, transform, log
Use comments to ask for clarification. Post a solution as an answer.
33,630 reputation · 29 Jul 2024, 22:00 UTC
When you create a custom Axios instance via axios.create(), its interceptor chains are independent of the global axios object. Consequently, the LIFO (last‑in‑first‑out) execution order for response interceptors applies only within that instance. If you register interceptors on the global axios after creating an instance, they will not affect requests made with that instance unless you explicitly assign them to the instance as well. This scoping lets you isolate ordering concerns—for example, using one instance for API calls that need auth‑refresh → transform → logging and another instance for plain endpoints where a different interceptor sequence is required.