How to Log Axios HTTP Requests and Responses
Logging outgoing HTTP traffic and incoming responses in Axios is essential for debugging, performance monitoring, and auditing API communication. This guide covers how to inspect network calls using native Axios interceptors, leverage specialized logging libraries, and implement best practices such as data sanitization for production environments.
1. Using Native Axios Interceptors
Axios provides built-in request and response interceptors that allow you to capture, modify, or log HTTP traffic before a request is sent or right after a response is received.
Implementing Request Logging
Request interceptors execute before the HTTP call is dispatched over the network.
import axios from 'axios';
// Add a request interceptor
axios.interceptors.request.use(
(config) => {
const { method, url, headers, data, params } = config;
console.log(`[HTTP Request] ${method?.toUpperCase()} ${url}`);
if (params) console.log('Params:', JSON.stringify(params, null, 2));
if (data) console.log('Payload:', JSON.stringify(data, null, 2));
return config;
},
(error) => {
console.error('[HTTP Request Error]', error);
return Promise.reject(error);
}
);Implementing Response Logging
Response interceptors catch both successful responses and HTTP error status codes (4xx, 5xx).
// Add a response interceptor
axios.interceptors.response.use(
(response) => {
const { status, statusText, config, data } = response;
console.log(`[HTTP Response] ${config.method?.toUpperCase()} ${config.url} - ${status} ${statusText}`);
console.log('Response Data:', JSON.stringify(data, null, 2));
return response;
},
(error) => {
if (error.response) {
// The server responded with a status code outside the 2xx range
console.error(
`[HTTP Error] ${error.config.method?.toUpperCase()} ${error.config.url} - Status: ${error.response.status}`
);
console.error('Error Body:', error.response.data);
} else if (error.request) {
// The request was made but no response was received
console.error('[HTTP Error] No response received:', error.request);
} else {
// Something happened in setting up the request
console.error('[HTTP Error] Request Setup Error:', error.message);
}
return Promise.reject(error);
}
);2. Using the
axios-logger Package
If you prefer pre-formatted console outputs with timestamps, headers,
and color-coded status messages, the axios-logger library
provides an out-of-the-box solution.
Installation
npm install axios-loggerConfiguration
import axios from 'axios';
import * as AxiosLogger from 'axios-logger';
const apiClient = axios.create();
// Attach logger interceptors
apiClient.interceptors.request.use(
AxiosLogger.requestLogger,
AxiosLogger.errorLogger
);
apiClient.interceptors.response.use(
AxiosLogger.responseLogger,
AxiosLogger.errorLogger
);
// Customize output formatting
AxiosLogger.setGlobalConfig({
prefixText: 'API_LOGGER',
dateFormat: 'HH:MM:ss',
status: true,
headers: false // Hide headers to reduce clutter
});3. Creating a Reusable Axios Instance
To prevent global scope pollution and ensure logs are only generated where intended, attach interceptors to a dedicated Axios instance rather than the default export.
import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
});
api.interceptors.request.use((config) => {
console.log(`Sending ${config.method.toUpperCase()} request to ${config.baseURL}${config.url}`);
return config;
});
export default api;4. Best Practices for HTTP Logging
- Sanitize Sensitive Data: Strip out
Authorizationtokens, API keys, passwords, and personally identifiable information (PII) before printing headers or bodies. - Environment Separation: Disable verbose payload logging in production environments to avoid high log-storage costs and security leaks.
- Measure Request Duration: Track execution time by attaching a timestamp in the request interceptor and calculating the difference inside the response interceptor.