Interceptors are functions that allow you to intercept, modify, or handle:
- Requests before they are sent
- Responses before they reach your code
They act like middleware for HTTP calls.
Most commonly used in Axios, but can be implemented manually for Fetch too.
✅ 1. Request Interceptors
These run before the request is sent.
Used for:
- Adding authentication tokens
- Setting default headers
- Logging requests
- Modifying request data
- Handling retries
Example (Axios request interceptor):
axios.interceptors.request.use(config => {
const token = localStorage.getItem("token");
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
✔ Automatically attaches JWT to every API call
✔ No need to manually add headers in each request
✅ 2. Response Interceptors
These run after the response is received but before it reaches your function.
Used for:
- Handling errors globally
- Refreshing tokens when expired
- Transforming response data
- Logging responses
Example (Axios response interceptor):
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
// token expired → refresh token logic
}
return Promise.reject(error);
}
);
✔ Centralized error handling
✔ No need to write try/catch everywhere
🎯 Why Are Interceptors Useful?
✔ 1. Avoid repeating logic
You don't have to add token headers in every request.
✔ 2. Centralized error management
Handle errors like 401, 403, 500 in one place.
✔ 3. Automatic token refresh
Detect expired token → call /refresh → retry request.
✔ 4. Request modification
Change URL, headers, or body dynamically.
✔ 5. Logging & debugging
Record request/response for analytics.
🔥 Interceptors with Fetch (Manual Implementation)
Fetch has no built-in interceptor system,
but you can wrap it:
const fetchWithInterceptor = async (url, options = {}) => {
// request interceptor
const token = localStorage.getItem("token");
options.headers = {
...options.headers,
Authorization: `Bearer ${token}`,
};
const response = await fetch(url, options);
// response interceptor
if (response.status === 401) {
console.log("Unauthorized request");
}
return response;
};
🎯 Short Interview Answer
Interceptors are middleware functions that allow you to modify or handle HTTP requests and responses globally. They run before requests are sent and after responses are received.
They are commonly used for adding tokens, centralizing error handling, logging, and auto-refreshing expired tokens.