Explain Codes LogoExplain Codes Logo

Accessing the Web Page's HTTP Headers in JavaScript

javascript
promises
callbacks
cors
Nikita BarsukovbyNikita Barsukov·Jan 28, 2025
TLDR

Fancy a quick dip into HTTP headers? Use the Fetch API:

fetch(window.location.href) .then(response => response.headers.forEach((value, key) => console.log(`${key}: ${value}`)));

Remember, not all headers are up for grabs; servers must give the "okay" first.

Diving deeper…

Now, let's get nerdy! The accessibility of headers boils down to two things: scope and security.

The scope of the problem

Since JavaScript is a client-side language, you don't get to see the headers of the initial response — it only flirts with headers of the requests it calls itself, typically via the XMLHttpRequest or Fetch API.

The security guard

The browser's same-origin policy and CORS (Cross-Origin Resource Sharing) are the gatekeepers here. They prevent access to headers that might let slip more than they should.

Possible workarounds

To access unavailable headers, you can either have a chat with the server or find ways around the server:

  1. Server-side fetch: Capture the headers server-side and send them as JSON to the client.
  2. Meta tags or variables: Incorporate headers into HTML server-side by crafting them into meta tags or JS variables.
  3. Playing the CORS game: Make your server add Access-Control-Expose-Headers in response headers for cross-origin calls.

Illustration

Imagine being inside a house (🏠), trying to look into the mailbox (📬) without stepping outside. This is your web page, and the HTTP headers are the mail:

🏠 Web Page: "I need to check the mail, but I don't want to leave the house." 📬 HTTP Headers: "I've got the information, but you need to step outside."

Accessing HTTP Headers in JavaScript is like yelling at the mailman (API) from your window:

// "Hey API, do you mind checking the mail for me?" fetch(window.location).then(response => { console.log(response.headers.get('Content-Type')); // 'text/html; charset=UTF-8' });

PS: Remember, the mailman can only bring you what he's allowed to carry!

The old AJAX way

If you're feeling nostalgic, here is the XMLHttpRequest (XHR) method:

var req = new XMLHttpRequest(); req.open('GET', document.location, false); req.send(null); /* * Time travelling back to 2005, * retrieving headers the AJAX way. */ var headers = req.getAllResponseHeaders().toLowerCase(); console.log(headers);

The server-side hustle

Getting the server to drop the headers into the HTML:

<!-- PHP: "This server, at your service!" --> <script> let headers = <?=json_encode(getallheaders())?>; /* * Server-side: "Dump all headers, pronto!" * JavaScript Console: "Got 'em all, boss!" */ console.log(headers); </script>

The CORS conundrum

Adding Access-Control- headers to the server response would be perfect for a cross-origin request:

Access-Control-Expose-Headers: x-custom-header Access-Control-Allow-Origin: *

In the Real World

In practice, you might come across some cases:

  • Third-Party APIs: Understand the API's CORS policy before taking headers.
  • Debugging headaches: Headers can provide clues, but the browser might hold some back.
  • Proxying: Server issues? Channel your requests through your own server.