[EN] What are Axios Interceptors?

Öztürk Şirin
2 min readMay 13, 2024

--

Source: Screenshot by Author

What are Interceptors?
Interceptors are a design pattern used to extend or modify the functionality of a program. In Axios, interceptors are special functions used to handle HTTP requests and responses. Request interceptors allow us to perform operations before sending requests, while response interceptors allow us to perform operations on the responses returned from the server.

Why should Axios interceptors be used?

  1. Reusability and modularity.
  2. Facilitation of error handling.
  3. Facilitation of security control and authorization validation processes.
  4. Handling network issues.
  5. Ease of use and flexibility.
  6. Performance and optimization.

Usage of Axios Interceptors
It has a simple usage and provides an advantage by being used within Axios without requiring additional setup.

const axiosInstance = axios.create({
baseURL: 'https://api.example.com',
headers: {
'Content-Type': 'application/json',
'Authorization': null
}
});

axiosInstance.interceptors.request.use(
function (config) {
// Operations to be performed before sending the request
console.log('sending request:', config);

// For example, we can add a session identifier to each request.
const accessToken = localStorage.getItem('accessToken');
if (accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`;
}

return config;
},
function (error) {
// Operations to be performed in case of request error
console.error('request error:', error);
return Promise.reject(error);
}
);

axiosInstance.interceptors.response.use(
function (response) {
// Operations to be performed when the response is successful
console.log('response:', response.data);
return response;
},
function (error) {
// Operations to be performed in case of response error
console.error('response error:', error);

// For example, assume that the session may have expired in case of a 401 (Unauthorized) error.
if (error.response.status === 401) {
// Actions like redirecting to refresh the session or redirecting the user to the login page can be performed.
console.log('Session expired. Redirecting...');
// For example, redirecting the user to the login page:
}
return Promise.reject(error);
}
);

// Example request

axiosInstance.get('/data')
.then(response => {
console.log('Response:', response.data);
})
.catch(error => {
console.error('Error:', error);
});

axiosInstance.post('/post-data', {
// Data you want to send
firstName: 'John',
lastName: 'Doe'
})
.then(response => {
console.log('Response:', response.data);
})
.catch(error => {
console.error('Error:', error);
});

🚀🚀 We can catch incoming errors like in this example and return to users or redirect between pages.
It makes it easier for us to view the errors and the body of each request in the console and take action.

Source: Taken by Author

Previous posts

--

--