How to Eject an Axios Interceptor
Axios interceptors are useful for modifying requests and responses
globally, but certain application lifecycles require them to be removed
to prevent memory leaks or redundant logic. This guide explains how to
properly remove or eject an interceptor from an Axios instance using the
built-in eject method.
Storing the Interceptor ID
When you attach an interceptor to an Axios instance using
.use(), Axios returns an integer representing that specific
interceptor's unique identifier. You must capture this ID in a variable
to reference it later when you want to remove it.
import axios from 'axios';
// Add a request interceptor and store its ID
const myRequestInterceptor = axios.interceptors.request.use(
(config) => {
// Modify request configuration
return config;
},
(error) => {
return Promise.reject(error);
}
);Ejecting the Interceptor
To remove the interceptor, call the .eject() method on
the corresponding interceptor type (request or
response) and pass the stored ID as the argument.
// Eject the request interceptor using its ID
axios.interceptors.request.eject(myRequestInterceptor);For response interceptors, the process is identical:
// Add a response interceptor
const myResponseInterceptor = axios.interceptors.response.use(
(response) => response,
(error) => Promise.reject(error)
);
// Eject the response interceptor
axios.interceptors.response.eject(myResponseInterceptor);Common Use Case: React Cleanup
In component-based frameworks like React, interceptors are often added inside lifecycle hooks and should be ejected during cleanup to prevent duplicate handlers when components unmount and remount.
import { useEffect } from 'react';
import axios from 'axios';
function DataFetcher() {
useEffect(() => {
const interceptorId = axios.interceptors.response.use(
(response) => response,
(error) => {
// Handle specific status codes
return Promise.reject(error);
}
);
// Clean up interceptor on unmount
return () => {
axios.interceptors.response.eject(interceptorId);
};
}, []);
return <div>Component Content</div>;
}Once .eject() is called, Axios removes the callback
handlers from its internal execution queue, ensuring future requests and
responses bypass that specific logic.