How to Log Axios Requests as cURL Commands
Logging HTTP requests as equivalent cURL commands simplifies debugging, API reproduction, and collaboration across development teams. This article outlines the primary techniques for generating and logging full cURL commands directly from Axios requests, including using popular npm packages and writing custom Axios interceptors.
Method 1: Using the
axios-curlirize Library
The fastest way to log cURL commands is by using the
axios-curlirize third-party library. It attaches
interceptors to your Axios instance automatically and outputs the
generated cURL command to the console.
Installation
npm install axios-curlirizeImplementation
const axios = require('axios');
const curlirize = require('axios-curlirize');
// Initialize curlirize with your Axios instance
curlirize(axios);
// Standard Axios request
axios.post('https://api.example.com/users', {
name: 'Jane Doe',
email: 'jane@example.com'
}, {
headers: {
'Authorization': 'Bearer sample_token_123',
'Content-Type': 'application/json'
}
})
.then(response => {
// Response handling
})
.catch(error => {
// Error handling
});When executed, this logs the command automatically:
curl -X POST -H "Authorization:Bearer sample_token_123" -H "Content-Type:application/json" --data "{\"name\":\"Jane Doe\",\"email\":\"jane@example.com\"}" "https://api.example.com/users"You can also pass custom logging callbacks to
curlirize:
curlirize(axios, (result, err) => {
const { command } = result;
if (err) {
console.error('Failed to generate cURL', err);
} else {
console.log('Generated cURL:', command);
}
});Method 2: Creating a Custom Axios Interceptor
If you prefer to avoid third-party dependencies, you can build a lightweight cURL generator using Axios request interceptors.
Implementation
const axios = require('axios');
function generateCurlCommand(config) {
const url = axios.getUri(config);
const method = (config.method || 'GET').toUpperCase();
const headers = config.headers || {};
let curl = `curl -X ${method} "${url}"`;
// Append headers
Object.keys(headers).forEach((key) => {
// Skip default headers if necessary
if (['common', 'get', 'post', 'put', 'delete', 'patch', 'head'].includes(key)) {
return;
}
curl += ` -H "${key}: ${headers[key]}"`;
});
// Append body data for POST, PUT, PATCH
if (config.data) {
const data = typeof config.data === 'object'
? JSON.stringify(config.data)
: config.data;
curl += ` --data '${data}'`;
}
return curl;
}
// Add the interceptor
axios.interceptors.request.use((config) => {
const curlCommand = generateCurlCommand(config);
console.log('[cURL Request]:', curlCommand);
return config;
}, (error) => {
return Promise.reject(error);
});Best Practices for Logging cURL Commands
- Sanitize Sensitive Data: Strip or mask sensitive
tokens such as passwords, API keys, or JWT tokens in the
Authorizationheader before writing logs to persistent storage. - Environment Restriction: Only enable cURL logging in local, development, or staging environments to prevent unintended data exposure in production logs.
- Query Parameter Handling: Always ensure URL
formatting accounts for query parameters defined in the
config.paramsobject by usingaxios.getUri(config)or manual query string serialization.