Debugging Axios Requests in React Applications
Debugging network requests is a crucial part of developing React applications. This article provides a straightforward guide on how to debug the Axios library in React, covering essential techniques such as using browser developer tools, implementing Axios interceptors for global logging, and handling errors programmatically to inspect API requests and responses effectively.
1. Inspecting the Browser Network Tab
The quickest way to debug Axios requests in React is to use your browser’s built-in Developer Tools.
- Open your React application in the browser.
- Press
F12or right-click and select Inspect to open Developer Tools. - Navigate to the Network tab.
- Filter the results by Fetch/XHR.
- Trigger your Axios request in the application.
Clicking on any request in the list allows you to inspect the Headers (request and response headers, status codes), Payload (data sent to the server), and Preview/Response (data returned by the server).
2. Using Axios Interceptors for Global Logging
Axios interceptors allow you to run your code or log data before a request is sent or after a response is received. This is ideal for setting up a centralized debugging system.
You can create an Axios instance with interceptors like this:
import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.example.com',
});
// Log outgoing requests
api.interceptors.request.use(
(config) => {
console.log(`[Axios Request] ${config.method?.toUpperCase()} - ${config.url}`, {
headers: config.headers,
data: config.data,
});
return config;
},
(error) => {
console.error('[Axios Request Error]', error);
return Promise.reject(error);
}
);
// Log incoming responses
api.interceptors.response.use(
(response) => {
console.log(`[Axios Response] ${response.status} - ${response.config.url}`, response.data);
return response;
},
(error) => {
console.error('[Axios Response Error]', error.response || error.message);
return Promise.reject(error);
}
);
export default api;By importing and using this api instance throughout your
React components instead of the default axios import, every
network event will automatically log detailed information to your
browser’s console.
3. Robust Error Handling in Components
When debugging, errors must be caught and parsed correctly. Axios
packages errors inside a structured object. You can extract precise
debugging information using a try...catch block:
import React, { useEffect } from 'react';
import api from './api'; // Import your configured Axios instance
const UserList = () => {
useEffect(() => {
const fetchUsers = async () => {
try {
const response = await api.get('/users');
console.log('Success:', response.data);
} catch (error) {
if (error.response) {
// The server responded with a status code outside the 2xx range
console.error('Server Error Data:', error.response.data);
console.error('Server Error Status:', error.response.status);
console.error('Server Error Headers:', error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.error('No response received:', error.request);
} else {
// Something happened in setting up the request
console.error('Axios Setup Error:', error.message);
}
}
};
fetchUsers();
}, []);
return <div>Check your console for Axios debugging logs.</div>;
};
export default UserList;4. Using External Logging Libraries
If you want cleaner, pre-formatted console outputs without writing
custom interceptor logs, you can use the axios-logger
package.
First, install the package:
npm install axios-loggerThen, attach it to your Axios instance:
import axios from 'axios';
import * as AxiosLogger from 'axios-logger';
const api = axios.create();
api.interceptors.request.use(AxiosLogger.requestLogger, AxiosLogger.errorLogger);
api.interceptors.response.use(AxiosLogger.responseLogger, AxiosLogger.errorLogger);
export default api;This library automatically formats requests, responses, headers, and execution times into highly readable console logs.