Reading response headers with Fetch API

There is a restriction to access response headers when you are using Fetch API over CORS. Due to this restriction, you can access only following standard headers:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

When you are writing code for Google Chrome extension, you are using CORS, hence you can't access all headers. If you control the server, you can return custom information in the response body instead of headers

More info on this restriction - https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types


If it's NOT CORS:

Fetch does not show headers while debugging or if you console.log response.

You have to use following way to access headers.

response.headers.get('x-auth-token')

From MDN

You can also get all the headers by accessing the entries Iterator.

// Display the key/value pairs
for (var pair of res.headers.entries()) {
   console.log(pair[0]+ ': '+ pair[1]);
}

Also, keep in mind this part:

For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names.


For backward compatibility with browsers that do not support ES2015 iterators (and probably also need fetch/Promise polyfills), the Headers.forEach function is the best option:

r.headers.forEach(function(value, name) {
    console.log(name + ": " + value);
});

Tested in IE11 with Bluebird as Promise polyfill and whatwg-fetch as fetch polyfill. Headers.entries(), Headers.keys() and Headers.values() does not work.


The Problem:

You may think this is a Frontend Problem.
It is a backend problem.
The browser will not allow to expose the Authorization header, unless if the Backend told the browser to expose it explicitly.

How To Solve It:

This worked for me.
In the backend (The API), add this to the response header:

response.headers.add("Access-Control-Expose-Headers","Authorization")

Why?

Security.
To prevent XSS exploits.
This request is supposed to be from backend to backend.
And the backend will set up the httpOnly cookie to the frontend.
So the authorization header should not be accessible by any third party JS package on your website.
If you think that it safe is to make the header accessible by frontend, do it.
But I recommend HttpOnly Cookies set up by the server backend to your browser immediately.

Reference:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers