How to Get Response Headers in Axios
When making an HTTP request using Axios, extracting response headers
is a straightforward process because Axios automatically attaches all
returned headers to the response object. This guide explains how to
access the complete headers object, retrieve specific header values, and
extract headers from error responses using both modern
async/await syntax and standard Promise handling.
Accessing Response Headers via the Response Object
When an Axios request resolves successfully, the resolved response
object contains a headers property. This property holds all
HTTP response headers sent by the server.
Example Using
async/await
const axios = require('axios');
async function fetchHeaders() {
try {
const response = await axios.get('https://api.example.com/data');
// Access all headers
console.log(response.headers);
// Access a specific header directly
const contentType = response.headers['content-type'];
console.log(`Content-Type: ${contentType}`);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchHeaders();Example Using Promises
(.then)
const axios = require('axios');
axios.get('https://api.example.com/data')
.then(response => {
// Access all headers
console.log(response.headers);
// Access a specific header
console.log(response.headers['content-type']);
})
.catch(error => {
console.error('Error:', error);
});Case Sensitivity and Axios Header Methods
In Axios (version 1.0.0 and above), the response.headers
object is an instance of AxiosHeaders. It normalizes header
names to lowercase for standard object access, but also provides
built-in methods for retrieving values safely regardless of case.
Using the .get() Method
The safest and most idiomatic way to retrieve a specific header in
modern Axios is the .get() method:
const response = await axios.get('https://api.example.com/data');
// Case-insensitive retrieval
const etag = response.headers.get('etag');
const contentLength = response.headers.get('Content-Length');Extracting Headers from Error Responses
If the server returns a non-2xx status code, Axios rejects the
Promise with an error object. To read the headers from a failed
response, check the error.response property before
accessing headers:
try {
const response = await axios.get('https://api.example.com/protected-resource');
} catch (error) {
if (error.response) {
// The request was made and the server responded with an error status
console.log('Error Status:', error.response.status);
console.log('Error Headers:', error.response.headers);
// Access a specific error header
const retryAfter = error.response.headers['retry-after'];
console.log(`Retry After: ${retryAfter}`);
} else if (error.request) {
// The request was made but no response was received
console.error('No response received from server');
} else {
// An error occurred setting up the request
console.error('Request Setup Error:', error.message);
}
}