Axios Interceptors in React: Interview Questions and Study Guide
What are Axios Interceptors?
Section titled “What are Axios Interceptors?”Axios Interceptors are functions that allow you to intercept and modify HTTP requests or responses before they are handled by .then() or .catch().
Common Use Cases
Section titled “Common Use Cases”- Add JWT token automatically
- Logging requests/responses
- Global error handling
- Refresh expired tokens
- Request/Response transformation
axios.interceptors.request.use( (config) => { console.log("Request sent"); return config; }, (error) => Promise.reject(error));Types of Interceptors
Section titled “Types of Interceptors”Request Interceptor
Section titled “Request Interceptor”Executed before the request is sent.
axios.interceptors.request.use(config => { config.headers.Authorization = `Bearer ${token}`; return config;});Response Interceptor
Section titled “Response Interceptor”Executed before the response reaches the component.
axios.interceptors.response.use( response => response, error => Promise.reject(error));Why Use Axios Interceptors?
Section titled “Why Use Axios Interceptors?”Without interceptors, every request must manually attach headers:
axios.get(url, { headers: { Authorization: token }});With an interceptor:
axios.interceptors.request.use(config => { config.headers.Authorization = token; return config;});The token is added automatically to every request.
Adding a JWT Token
Section titled “Adding a JWT Token”axios.interceptors.request.use(config => { const token = localStorage.getItem("token");
if (token) { config.headers.Authorization = `Bearer ${token}`; }
return config;});This centralizes authentication logic.
Global Error Handling
Section titled “Global Error Handling”axios.interceptors.response.use( response => response, error => { if (error.response.status === 500) { alert("Server Error"); }
return Promise.reject(error); });Benefits:
- Common error handling
- Avoid duplicate code
Redirect on 401 Unauthorized
Section titled “Redirect on 401 Unauthorized”axios.interceptors.response.use( response => response, error => { if (error.response.status === 401) { window.location.href = "/login"; }
return Promise.reject(error); });Creating a Reusable Axios Instance
Section titled “Creating a Reusable Axios Instance”import axios from "axios";
const api = axios.create({ baseURL: "https://api.example.com", timeout: 10000});
export default api;Attach an interceptor:
api.interceptors.request.use(config => { config.headers.Authorization = `Bearer ${localStorage.getItem("token")}`;
return config;});Usage:
api.get("/users");Interceptor Execution Order
Section titled “Interceptor Execution Order”flowchart TD
A["Request Interceptor(s)"] --> B[HTTP Request]
B --> C[Server]
C --> D[HTTP Response]
D --> E["Response Interceptor(s)"]
E --> F[Application]
| Type | Execution |
|---|---|
| Request | Last In, First Out (LIFO) |
| Response | First In, First Out (FIFO) |
Request example:
axios.interceptors.request.use(req1);axios.interceptors.request.use(req2);Execution:
req2 -> req1 -> APIResponse example:
axios.interceptors.response.use(res1);axios.interceptors.response.use(res2);Execution:
API -> res1 -> res2Removing an Interceptor
Section titled “Removing an Interceptor”const interceptorId =axios.interceptors.request.use(config => { return config;});
axios.interceptors.request.eject(interceptorId);Useful to avoid duplicate registrations and memory leaks.
Refreshing an Expired Token
Section titled “Refreshing an Expired Token”axios.interceptors.response.use( response => response, async error => {
if (error.response.status === 401) {
const refreshResponse = await axios.post("/refresh-token");
const newToken = refreshResponse.data.token;
localStorage.setItem("token", newToken);
error.config.headers.Authorization = `Bearer ${newToken}`;
return axios(error.config); }
return Promise.reject(error); });Prevent Infinite Retry Loops
Section titled “Prevent Infinite Retry Loops”axios.interceptors.response.use( response => response, async error => {
const originalRequest = error.config;
if ( error.response.status === 401 && !originalRequest._retry ) { originalRequest._retry = true;
// refresh token logic }
return Promise.reject(error); });Middleware vs Axios Interceptors
Section titled “Middleware vs Axios Interceptors”| Middleware | Axios Interceptor |
|---|---|
| Runs on server | Runs on client |
| Express/Spring Boot | Axios |
| Handles request pipeline | Handles HTTP requests/responses |
| Server-side | Browser-side |
API Logging
Section titled “API Logging”Request logging:
axios.interceptors.request.use(config => { console.log(config.method, config.url); return config;});Response logging:
axios.interceptors.response.use(response => { console.log(response.status, response.config.url); return response;});Real-World Uses
Section titled “Real-World Uses”- JWT Authentication
- Token Refresh
- Request Logging
- Response Logging
- Error Handling
- Loading Spinner Management
- Retry Failed Requests
- API Metrics Collection
Senior-Level Interview Questions
Section titled “Senior-Level Interview Questions”Why use an Axios instance instead of global interceptors?
Section titled “Why use an Axios instance instead of global interceptors?”Advantages:
- Better modularity
- Different APIs can have different configurations
- Easier testing
- Avoid interceptor conflicts
const authApi = axios.create();const publicApi = axios.create();How would you handle concurrent 401 responses?
Section titled “How would you handle concurrent 401 responses?”If multiple requests fail simultaneously:
- Refresh the token only once.
- Queue the remaining failed requests.
- Retry them after the refreshed token is available.
This avoids multiple refresh-token requests.
Common Challenges
Section titled “Common Challenges”- Infinite retry loops
- Duplicate interceptor registration
- Concurrent token refresh issues
- Memory leaks
- Global error handling affecting unrelated APIs
One-Line Interview Answer
Section titled “One-Line Interview Answer”Axios Interceptors are middleware-like functions that intercept HTTP requests and responses globally, commonly used for JWT authentication, token refresh, logging, and centralized error handling.
Summary
Section titled “Summary”- Axios provides request and response interceptors for centralized HTTP handling.
- Interceptors simplify authentication, logging, error handling, and token refresh.
- Request interceptors execute in LIFO order, while response interceptors execute in FIFO order.
- Use reusable Axios instances for modular and maintainable applications.
- Prevent infinite retry loops and duplicate interceptor registration in production applications.