When developing web applications, efficient request and response handling is crucial for smooth communication with APIs. Interceptors in Axios provide a powerful way to handle requests and responses globally, allowing you to add custom logic, modify headers, handle errors, and more.
In this comprehensive guide, we’ll explore how to use Axios interceptors to handle requests and responses effectively. We’ll cover setting up Axios, implementing request and response interceptors, handling errors, removing interceptors, and advanced usage techniques. By the end of this article, you’ll have a thorough understanding of how to leverage Axios interceptors to enhance your application’s HTTP communication.
Understanding Interceptors in Axios
Interceptors are functions that Axios calls for every request or response before the request is sent or the response is received. They allow you to modify the request or response, add headers, log information, and handle errors globally. This centralized approach simplifies the management of HTTP requests and responses in your application.
Use Cases for Interceptors
Interceptors are used in various scenarios, such as:
- Adding Authorization Tokens: Automatically attaching authentication tokens to every request.
- Logging: Logging request and response details for debugging purposes.
- Error Handling: Managing errors globally, such as redirecting to a login page on a 401 Unauthorized response.
- Transforming Requests/Responses: Modifying the request or response data before it is sent or processed.
Setting Up Axios in Your Project
To start using Axios and interceptors, you need to set it up in your project. You can install Axios via npm/yarn or include it via a CDN.
Installing Axios via npm/yarn
If you’re using npm or yarn, you can install Axios with a simple command.
Using npm:
npm install axios
Using yarn:
yarn add axios
After installation, you can import Axios in your JavaScript files:
import axios from 'axios';
Setting Up Axios via CDN
If you prefer to include Axios via a Content Delivery Network (CDN), you can add the following script tag to your HTML file:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
This approach is useful for quick setups or for use in environments where a package manager is not available. When included via CDN, Axios is available globally as axios.
Implementing Request Interceptors
Request interceptors are functions that run before a request is sent. They are useful for tasks such as adding authorization headers, logging request details, or modifying request data.
Using npm/yarn:
import axios from 'axios';
// Add a request interceptor
axios.interceptors.request.use(
config => {
console.log('Request made with ', config);
config.headers.Authorization = 'Bearer your_token_here';
return config;
},
error => {
return Promise.reject(error);
}
);
// Function to make a request
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the function to fetch data
fetchData();
Using CDN:
<script>
// Add a request interceptor
axios.interceptors.request.use(
config => {
console.log('Request made with ', config);
config.headers.Authorization = 'Bearer your_token_here';
return config;
},
error => {
return Promise.reject(error);
}
);
// Function to make a request
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the function to fetch data
fetchData();
</script>
In this example, we add a request interceptor using axios.interceptors.request.use. The interceptor logs the request configuration and adds an Authorization header with a bearer token. The fetchData function makes a GET request to https://api.example.com/data, and the request interceptor ensures that the token is included in the request headers. The response data is logged if the request is successful, and any errors are caught and logged.
Implementing Response Interceptors
Response interceptors are functions that run after a response is received but before it is processed by your application. They are useful for tasks such as logging response details, modifying response data, or handling errors globally.
Using npm/yarn:
import axios from 'axios';
// Add a response interceptor
axios.interceptors.response.use(
response => {
console.log('Response received', response);
return response;
},
error => {
console.log('Error response', error.response);
return Promise.reject(error);
}
);
// Function to make a request
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the function to fetch data
fetchData();
Using CDN:
<script>
// Add a response interceptor
axios.interceptors.response.use(
response => {
console.log('Response received', response);
return response;
},
error => {
console.log('Error response', error.response);
return Promise.reject(error);
}
);
// Function to make a request
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the function to fetch data
fetchData();
</script>
In this example, we add a response interceptor using axios.interceptors.response.use. The interceptor logs the response details and returns the response for further processing. If an error occurs, it logs the error response and rejects the promise. The fetchData function makes a GET request to https://api.example.com/data, and the response interceptor logs the response details. If the request is successful, the response data is logged, and any errors are caught and logged.
Handling Errors with Interceptors
Error handling is a crucial aspect of HTTP communication. Interceptors provide a centralized way to manage errors, such as retrying requests, redirecting users, or displaying error messages.
Using npm/yarn:
import axios from 'axios';
// Add a request interceptor
axios.interceptors.request.use(
config => {
console.log('Request made with ', config);
config.headers.Authorization = 'Bearer your_token_here';
return config;
},
error => {
return Promise.reject(error);
}
);
// Add a response interceptor
axios.interceptors.response.use(
response => {
console.log('Response received', response);
return response;
},
error => {
if (error.response && error.response.status === 401) {
console.log('Unauthorized, logging out...');
// Redirect to login page or logout user
}
return Promise.reject(error);
}
);
// Function to make a request
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the function to fetch data
fetchData();
Using CDN:
<script>
// Add a request interceptor
axios.interceptors.request.use(
config => {
console.log('Request made with ', config);
config.headers.Authorization = 'Bearer your_token_here';
return config;
},
error => {
return Promise.reject(error);
}
);
// Add a response interceptor
axios.interceptors.response.use(
response => {
console.log('Response received', response);
return response;
},
error => {
if (error.response && error.response.status === 401)
console.log('Unauthorized, logging out...');
// Redirect to login page or logout user
}
return Promise.reject(error);
}
);
// Function to make a request
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the function to fetch data
fetchData();
</script>
In this example, we add request and response interceptors. The request interceptor adds an Authorization header, while the response interceptor handles errors globally. If a 401 Unauthorized error occurs, the interceptor logs a message and can redirect the user to a login page or perform a logout action. The fetchData function makes a GET request to https://api.example.com/data. The interceptors handle the request and response, logging details and managing errors as needed.
Removing Interceptors
In some cases, you may need to remove interceptors, such as when they are no longer needed or when you want to apply different logic temporarily. Axios provides a way to remove interceptors by storing their reference and using the eject method.
Using npm/yarn:
import axios from 'axios';
// Add a request interceptor
const requestInterceptor = axios.interceptors.request.use(
config => {
console.log('Request made with ', config);
config.headers.Authorization = 'Bearer your_token_here';
return config;
},
error => {
return Promise.reject(error);
}
);
// Function to remove the request interceptor
const removeInterceptor = () => {
axios.interceptors.request.eject(requestInterceptor);
console.log('Request interceptor removed');
};
// Function to make a request
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the function to fetch data
fetchData();
// Remove the interceptor
removeInterceptor();
Using CDN:
<script>
// Add a request interceptor
const requestInterceptor = axios.interceptors.request.use(
config => {
console.log('Request made with ', config);
config.headers.Authorization = 'Bearer your_token_here';
return config;
},
error => {
return Promise.reject(error);
}
);
// Function to remove the request interceptor
const removeInterceptor = () => {
axios.interceptors.request.eject(requestInterceptor);
console.log('Request interceptor removed');
};
// Function to make a request
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the function to fetch data
fetchData();
// Remove the interceptor
removeInterceptor();
</script>
In this example, we add a request interceptor and store its reference in the requestInterceptor variable. The removeInterceptor function uses axios.interceptors.request.eject to remove the interceptor by passing the stored reference. The fetchData function makes a GET request to https://api.example.com/data. After calling fetchData, we call removeInterceptor to remove the interceptor, ensuring it no longer affects subsequent requests. Removing interceptors allows for flexible management of request and response handling logic.
Advanced Usage of Interceptors
Advanced usage of interceptors includes chaining multiple interceptors and performing complex tasks such as retrying failed requests, transforming data, and conditionally modifying requests or responses.
Using npm/yarn:
import axios from 'axios';
// Add a request interceptor
axios.interceptors.request.use(
config => {
console.log('Request made with ', config);
config.headers.Authorization = 'Bearer your_token_here';
return config;
},
error => {
return Promise.reject(error);
}
);
// Add another request interceptor
axios.interceptors.request.use(
config => {
console.log('Second request interceptor');
config.headers['Custom-Header'] = 'CustomValue';
return config;
},
error => {
return Promise.reject(error);
}
);
// Add a response interceptor
axios.interceptors.response.use(
response => {
console.log('Response received', response);
return response;
},
error => {
if (error.response && error.response.status === 500) {
console.log('Internal Server Error, retrying...');
// Retry logic here
}
return Promise.reject(error);
}
);
// Function to make a request
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the function to fetch data
fetchData();
Using CDN:
<script>
// Add a request interceptor
axios.interceptors.request.use(
config => {
console.log('Request made with ', config);
config.headers.Authorization = 'Bearer your_token_here';
return config;
},
error => {
return Promise.reject(error);
}
);
// Add another request interceptor
axios.interceptors.request.use(
config => {
console.log('Second request interceptor');
config.headers['Custom-Header'] = 'CustomValue';
return config;
},
error => {
return Promise.reject(error);
}
);
// Add a response interceptor
axios.interceptors.response.use(
response => {
console.log('Response received', response);
return response;
},
error => {
if (error.response && error.response.status === 500) {
console.log('Internal Server Error, retrying...');
// Retry logic here
}
return Promise.reject(error);
}
);
// Function to make a request
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the function to fetch data
fetchData();
</script>
In this example, we chain multiple request interceptors and add a response interceptor. The first request interceptor adds an Authorization header, while the second request interceptor adds a custom header. The response interceptor handles errors and retries the request if a 500 Internal Server Error occurs. The fetchData function makes a GET request to https://api.example.com/data, and the interceptors handle the request and response, logging details and managing errors as needed. Chaining interceptors allows for complex request and response handling logic, enabling you to perform multiple tasks in a single request cycle.
Conclusion
In this article, we explored how to use Axios interceptors to handle requests and responses effectively. We covered setting up Axios, implementing request and response interceptors, handling errors, removing interceptors, and advanced usage techniques like chaining interceptors. These tools help streamline and enhance the efficiency of HTTP communication in your web applications.
The examples and concepts discussed provide a solid foundation for working with Axios interceptors in your projects. However, there is much more to explore. I encourage you to experiment further with interceptors, integrating them into your applications to handle API interactions efficiently and effectively.