Exposing Response Headers
You'll learn how to make custom response headers readable in cross-origin fetch requests using Access-Control-Expose-Headers.
The Problem with Hidden Headers
When you make a cross-origin request, the browser receives all the response headers from the server, but JavaScript can only read a small "safe list" by default. This safe list includes basic headers like Content-Type, Content-Length, and Cache-Control. Any custom headers the server sends (like X-Rate-Limit-Remaining or X-Total-Count) are invisible to your code—even though they arrived!
Think of it like receiving a package with extra tracking stickers, but someone puts a cover over them. The stickers are there, but you can't see them unless the sender explicitly says "it's okay to look."
The Solution: Access-Control-Expose-Headers
The server must explicitly list which custom headers JavaScript is allowed to read by sending an Access-Control-Expose-Headers header:
// On the server:
// Access-Control-Expose-Headers: X-Rate-Limit, X-Total-Count
// Now in your JavaScript:
fetch('https://api.example.com/data')
.then(response => {
// These work because they're exposed:
const rateLimit = response.headers.get('X-Rate-Limit');
const total = response.headers.get('X-Total-Count');
console.log(`Rate limit: ${rateLimit}, Total: ${total}`);
});
Without the Access-Control-Expose-Headers header on the server, response.headers.get('X-Rate-Limit') would return null even if the header exists.
Key Takeaway: In cross-origin requests, custom response headers are hidden from JavaScript unless the server explicitly exposes them with the Access-Control-Expose-Headers header—you can't read what isn't exposed, even if it was sent.