- Centralized Logic: Avoid repeating the same logic (like adding auth headers) in multiple components.
- Global Error Handling: Catch and handle errors in one place instead of scattering error handling throughout your app.
- Request Transformation: Modify requests before they are sent (e.g., adding a timestamp).
- Response Transformation: Modify responses before they are processed (e.g., unwrapping data).
- Authentication: Automatically add authentication tokens to requests.
Hey guys! Ever found yourself needing to tweak HTTP requests or responses globally in your React app? Maybe you need to add an authentication token to every outgoing request, or handle errors in a consistent way across your application. That's where Axios interceptors come to the rescue! In this guide, we're diving deep into Axios interceptors with React, showing you how to use them effectively with clear examples. So, buckle up and let's make your API interactions smoother and more maintainable!
What are Axios Interceptors?
Axios interceptors are functions that Axios calls for every request and response. You can intercept requests before they are sent and responses before they are handled by .then() or .catch(). Think of them as middleware for your HTTP requests. They allow you to modify the request or response config, handle errors globally, or perform actions like logging.
Why Use Interceptors?
Setting Up Axios in React
Before we dive into interceptors, let's make sure you have Axios set up in your React project. If you haven't already, install Axios using npm or yarn:
npm install axios
# or
yarn add axios
Now, let's create an Axios instance that we can use throughout our application. This is a good practice because it allows you to configure Axios with default settings, such as the base URL for your API. Create a file named axios.js (or similar) in your src directory:
// src/axios.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://your-api-base-url.com',
timeout: 10000, // Optional: Set a timeout for requests
headers: {
'Content-Type': 'application/json',
},
});
export default instance;
In this setup:
- We import
axiosfrom theaxiospackage. - We create an instance of Axios using
axios.create(). This allows us to configure Axios with default settings. - We set the
baseURLto the base URL of our API. This means that every request we make using this instance will automatically prepend this URL. - We set a
timeoutof 10000 milliseconds (10 seconds). If a request takes longer than this, Axios will automatically cancel it. - We set the
Content-Typeheader toapplication/json. This tells the server that we are sending JSON data.
Now that we have our Axios instance set up, we can import it into our React components and use it to make API requests.
Creating and Using Axios Interceptors
Now for the fun part! Let's create some interceptors. We'll start with a simple example: adding a request interceptor to log every outgoing request. Open your axios.js file and add the following code:
// src/axios.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://your-api-base-url.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// Request interceptor
instance.interceptors.request.use(
(config) => {
// Log the request
console.log('Request:', config);
return config; // Must return the config!
},
(error) => {
// Do something with request error
console.error('Request Error:', error);
return Promise.reject(error);
}
);
// Response interceptor
instance.interceptors.response.use(
(response) => {
// Log the response
console.log('Response:', response);
return response; // Must return the response!
},
(error) => {
// Do something with response error
console.error('Response Error:', error);
return Promise.reject(error);
}
);
export default instance;
In this example:
- We use
instance.interceptors.request.use()to add a request interceptor. - The first function is called before the request is sent. It receives the request
configobject as an argument. You must return theconfigobject for the request to proceed. - The second function is called if there is an error when creating the request. It receives the error object as an argument. You should return a rejected
Promiseto propagate the error. - We use
instance.interceptors.response.use()to add a response interceptor. - The first function is called when a response is received. It receives the response object as an argument. You must return the response object for the response to be processed.
- The second function is called if there is an error when receiving the response. It receives the error object as an argument. You should return a rejected
Promiseto propagate the error.
Adding an Authentication Token
One of the most common use cases for interceptors is adding an authentication token to every outgoing request. Let's say you have a token stored in localStorage. You can add an interceptor to automatically add the token to the Authorization header:
// src/axios.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://your-api-base-url.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
instance.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
console.error('Request Error:', error);
return Promise.reject(error);
}
);
instance.interceptors.response.use(
(response) => {
console.log('Response:', response);
return response;
},
(error) => {
console.error('Response Error:', error);
return Promise.reject(error);
}
);
export default instance;
Now, every request will automatically include the Authorization header with the token.
Handling Errors Globally
Another powerful use case for interceptors is handling errors globally. You can catch errors and display a notification to the user, redirect them to a login page, or perform other actions.
// src/axios.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://your-api-base-url.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
instance.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
console.error('Request Error:', error);
return Promise.reject(error);
}
);
instance.interceptors.response.use(
(response) => {
console.log('Response:', response);
return response;
},
(error) => {
console.error('Response Error:', error);
// Handle different error codes
if (error.response) {
switch (error.response.status) {
case 401:
// Redirect to login page
window.location.href = '/login';
break;
case 403:
// Show a forbidden message
alert('You do not have permission to access this resource.');
break;
case 500:
// Show a server error message
alert('A server error occurred. Please try again later.');
break;
default:
// Show a generic error message
alert('An error occurred. Please try again later.');
}
} else {
// Handle network errors
alert('Network error. Please check your internet connection.');
}
return Promise.reject(error);
}
);
export default instance;
Now, all API errors will be caught by the interceptor, and the appropriate action will be taken based on the error code.
Using the Axios Instance in React Components
Now that we have our Axios instance with interceptors set up, let's use it in a React component. Import the instance and use it to make API requests:
// src/components/MyComponent.jsx
import React, { useState, useEffect } from 'react';
import axiosInstance from '../axios'; // Import the Axios instance
const MyComponent = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axiosInstance.get('/api/data');
setData(response.data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
return (
<div>
<h1>Data</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default MyComponent;
In this component:
- We import the Axios instance from
../axios.js. - We use
axiosInstance.get()to make a GET request to/api/data. - The interceptors we defined in
axios.jswill automatically be applied to this request.
Removing Interceptors
Sometimes you may need to remove an interceptor. For example, you might want to disable an interceptor for a specific request or component. Axios provides a way to remove interceptors using the eject method. When you call axios.interceptors.request.use or axios.interceptors.response.use, it returns an ID. You can use this ID to remove the interceptor later.
Here's how you can remove an interceptor:
const requestInterceptorId = instance.interceptors.request.use(/* ... */);
const responseInterceptorId = instance.interceptors.response.use(/* ... */);
// To remove the interceptor:
instance.interceptors.request.eject(requestInterceptorId);
instance.interceptors.response.eject(responseInterceptorId);
Make sure you store the interceptor ID when you create the interceptor so that you can remove it later.
Conclusion
Axios interceptors are a powerful tool for managing HTTP requests and responses in your React applications. They allow you to centralize logic, handle errors globally, and transform requests and responses. By using interceptors, you can make your API interactions more maintainable and easier to manage. So go ahead, give them a try, and take your React apps to the next level!
Lastest News
-
-
Related News
American Nuclear Society: Who Are The Members?
Alex Braham - Nov 13, 2025 46 Views -
Related News
Columbia MO Utility Bills: What's The Average?
Alex Braham - Nov 13, 2025 46 Views -
Related News
Understanding OSCOS Dividend Policy: A Comprehensive Guide
Alex Braham - Nov 13, 2025 58 Views -
Related News
Rublev Vs. Medvedev: ATP Showdown 2022
Alex Braham - Nov 9, 2025 38 Views -
Related News
Indonesia Vs Brunei: Match Date & Info
Alex Braham - Nov 9, 2025 38 Views