Sanitizing Sensitive Headers in Axios Logs
This article explains how to sanitize sensitive request headers when logging HTTP requests using the Axios library. By implementing Axios request interceptors and redaction logic, developers can prevent credentials, tokens, and personally identifiable information (PII) from leaking into logging systems while maintaining useful debugging telemetry.
1. Identify Sensitive Headers
Before modifying your logging workflow, define which headers contain confidential information. Common headers that require sanitization include:
Authorization(Bearer tokens, Basic authentication credentials)CookieandSet-Cookie(Session identifiers)X-API-Keyor custom API key headersProxy-Authorization
2. Implement an Axios Request Interceptor
Axios interceptors allow you to inspect and modify request configurations before the HTTP call is dispatched over the network. Using a request interceptor ensures that every outgoing request is intercepted and logged consistently.
3. Clone and Redact Header Values
To prevent the actual network request from losing its authentication
credentials, create a shallow copy of the headers for logging purposes
instead of mutating the original config.headers object
directly.
Create a sanitization function that iterates through header keys in a
case-insensitive manner and replaces sensitive values with a masked
string like [REDACTED].
4. Code Implementation
Below is a complete implementation showing how to safely sanitize and log Axios headers:
const axios = require('axios');
// List of header names to mask (lowercase for normalization)
const SENSITIVE_HEADERS = new Set([
'authorization',
'cookie',
'set-cookie',
'x-api-key',
'proxy-authorization'
]);
/**
* Creates a sanitized copy of the request headers.
* @param {Object} headers - The Axios request headers.
* @returns {Object} A new object with sensitive header values masked.
*/
function sanitizeHeaders(headers = {}) {
const sanitized = {};
for (const [key, value] of Object.entries(headers)) {
if (SENSITIVE_HEADERS.has(key.toLowerCase())) {
sanitized[key] = '[REDACTED]';
} else {
sanitized[key] = value;
}
}
return sanitized;
}
// Create an Axios instance
const apiClient = axios.create({
baseURL: 'https://api.example.com'
});
// Add the request interceptor for secure logging
apiClient.interceptors.request.use(
(config) => {
// Extract and sanitize headers specifically for the logger
const logSafeHeaders = sanitizeHeaders(config.headers);
// Log the request metadata safely
console.log({
method: config.method?.toUpperCase(),
url: config.url,
headers: logSafeHeaders,
timestamp: new Date().toISOString()
});
// Return the original config so the actual request remains intact
return config;
},
(error) => {
return Promise.reject(error);
}
);5. Handle Partial Redaction (Optional)
If your debugging process requires verifying the format or type of a
credential without exposing the secret itself (for example, confirming a
token starts with Bearer ), you can mask only the sensitive
substring:
function maskToken(value) {
if (typeof value === 'string' && value.startsWith('Bearer ')) {
return `Bearer ${value.slice(7, 11)}...[REDACTED]`;
}
return '[REDACTED]';
}6. Verify Response and Error Interceptors
Sensitive headers can also appear in error objects when a request
fails. Implement an axios.interceptors.response.use error
handler to sanitize error.config.headers before writing
error details to application logs.