Reading Response Headers
You'll learn how to extract and inspect HTTP response headers from fetch() responses using the built-in Headers API.
Understanding Response Headers
When your fetch request completes, the server doesn't just send back data—it also sends metadata about that data in response headers. Think of headers like a shipping label on a package: they tell you important information like content type, caching rules, timestamps, and custom server messages, separate from the actual contents inside.
The Response object returned by fetch() includes a headers property that gives you access to all these headers.
Accessing Individual Headers
You can read a specific header using the get() method on the headers object:
fetch('https://api.example.com/data')
.then(response => {
const contentType = response.headers.get('Content-Type');
const cacheControl = response.headers.get('Cache-Control');
console.log('Content-Type:', contentType);
console.log('Cache-Control:', cacheControl);
return response.json();
});
Iterating Through All Headers
The Headers API is iterable, meaning you can loop through every header using for...of or convert it to an array:
fetch('https://api.example.com/data')
.then(response => {
for (const [key, value] of response.headers) {
console.log(`${key}: ${value}`);
}
return response.json();
});
This is useful for debugging or logging purposes, letting you see exactly what metadata the server sent back.
Key Takeaway: Use response.headers.get(name) to access specific response headers, and iterate with for...of to inspect all headers returned by the server.