What is getResponseHeader()?
The getResponseHeader() method of the XMLHttpRequest interface returns the string containing the text of a particular header's value from the HTTP response. This method has been a cornerstone of client-side HTTP communication since the early days of Ajax and continues to be relevant in modern web development workflows.
Understanding how to properly utilize this method enables developers to implement sophisticated features such as content-type detection, caching strategy optimization, authentication flow handling, and rate limit monitoring. When building applications with frameworks like Next.js, knowing how to extract headers from API responses can help implement efficient caching mechanisms, handle authentication tokens, and optimize data fetching strategies.
The method operates on response headers that have been received from the server, providing access to information such as content type, content length, caching directives, and custom headers. This capability is particularly valuable when building API clients, implementing file upload handlers, or creating applications that need to adapt their behavior based on server-provided metadata.
1const xhr = new XMLHttpRequest();2xhr.open('GET', '/api/data', true);3 4xhr.onreadystatechange = function() {5 if (xhr.readyState === xhr.HEADERS_RECEIVED) {6 const contentType = xhr.getResponseHeader('Content-Type');7 console.log('Content-Type:', contentType);8 }9};10 11xhr.send();Syntax and Parameters
Method Signature
const headerValue = xhr.getResponseHeader(headerName);
Parameter Details
The headerName parameter is a string indicating the name of the header you want to return the text value of. The search for the header name is case-insensitive, meaning "Content-Type", "content-type", and "CONTENT-TYPE" will all return the same value. This case-insensitive matching aligns with HTTP specification requirements and simplifies header retrieval in JavaScript code.
Return Value
- String: The header's text value
- null: If the response has not been received or the header doesn't exist
When multiple response headers exist with the same name, their values are returned as a single concatenated string, separated by a comma and space. The method returns the value as a UTF byte sequence, which ensures proper handling of international characters and encoding schemes in header values.
Understanding these return behaviors is essential for building robust JavaScript applications that handle diverse API responses gracefully.
What getResponseHeader() enables in your applications
Content-Type Detection
Determine how to parse response data based on the MIME type specified in headers.
Caching Optimization
Read Cache-Control and ETag headers to implement efficient caching strategies.
Rate Limit Monitoring
Track API usage limits using X-RateLimit headers from service responses.
Authentication Handling
Extract and process authentication-related headers for secure data flow.
Practical Use Cases
Caching Implementation
Implement intelligent caching in your applications by checking response headers:
function fetchWithCaching(url, cacheKey) {
return new Promise((resolve, reject) => {
const cachedData = localStorage.getItem(cacheKey);
if (cachedData) {
const cached = JSON.parse(cachedData);
const cacheControl = cached.headers['cache-control'];
const maxAge = cacheControl
? parseInt(cacheControl.match(/max-age=(\d+)/)?.[1] || '0')
: 0;
if (Date.now() - cached.timestamp < maxAge * 1000) {
resolve(cached.data);
return;
}
}
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function() {
if (xhr.status === 200) {
const cacheControl = xhr.getResponseHeader('Cache-Control');
const etag = xhr.getResponseHeader('ETag');
const cacheData = {
data: xhr.response,
headers: { 'cache-control': cacheControl, 'etag': etag },
timestamp: Date.now()
};
localStorage.setItem(cacheKey, JSON.stringify(cacheData));
resolve(xhr.response);
}
};
xhr.onerror = () => reject(new Error('Network error'));
xhr.send();
});
}
This caching pattern is particularly valuable when building high-performance web applications that minimize unnecessary network requests while ensuring data freshness. When combined with proper SEO practices, efficient caching can significantly improve both user experience and search engine rankings.
| Header | Purpose | Example Value |
|---|---|---|
| Content-Type | MIME type of response body | application/json |
| Cache-Control | Caching directives | max-age=3600 |
| ETag | Resource version identifier | "abc123" |
| Content-Length | Response size in bytes | 12345 |
| Last-Modified | Last modification date | Wed, 21 Oct 2025 07:28:00 GMT |
| X-RateLimit-Remaining | API requests remaining | 99 |
Best Practices
1. Always Check for null Returns
const contentType = xhr.getResponseHeader('Content-Type');
if (contentType) {
console.log('Content-Type:', contentType);
} else {
console.warn('Header not available');
}
2. Time Header Access Properly
Headers are only available after readyState reaches HEADERS_RECEIVED (state 2). Attempting to access headers before this point will return null.
3. Use ReadyState Constants
xhr.onreadystatechange = function() {
if (xhr.readyState === xhr.HEADERS_RECEIVED) {
// Headers are now available
}
if (xhr.readyState === xhr.DONE) {
// Full response available
}
};
4. Combine with setRequestHeader()
For complete header management, use both methods together. Use setRequestHeader() to send request headers and getResponseHeader() to read response headers:
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
// ... later ...
const rateLimit = xhr.getResponseHeader('X-RateLimit-Remaining');
Following these best practices ensures your API integrations are robust, secure, and maintainable.
getResponseHeader() vs Fetch API
The Fetch API provides a modern alternative with the Response.headers interface:
// Modern Fetch API approach
fetch('/api/data')
.then(response => {
const contentType = response.headers.get('Content-Type');
const cacheControl = response.headers.get('Cache-Control');
return response.json();
});
Choose XMLHttpRequest.getResponseHeader() when:
- Supporting older browsers without Fetch API
- Maintaining existing XHR-based codebases
- Needing synchronous request capabilities (deprecated but available)
Choose Fetch API for new projects:
- Cleaner Promise-based design
- More consistent API across browsers
- Better streaming support
For modern web development and React applications, the Fetch API is generally recommended. However, XMLHttpRequest knowledge remains valuable for legacy support and understanding browser HTTP communication fundamentals. Our web development team can help you modernize your HTTP client implementations.
Frequently Asked Questions
Sources
- MDN Web Docs: getResponseHeader() - Official documentation for the XMLHttpRequest.getResponseHeader() method
- WHATWG XMLHttpRequest Standard - Authoritative living standard specification
- MDN Web Docs: XMLHttpRequest - Complete XMLHttpRequest API reference
- MDN Web Docs: Using XMLHttpRequest - Practical usage patterns and best practices