486

How do I access a page's HTTP response headers via JavaScript?

Related to this question, which was modified to ask about accessing two specific HTTP headers.

Related:
How do I access the HTTP request header fields via JavaScript?

Community
  • 1
  • 1
keparo
  • 33,450
  • 13
  • 60
  • 66
  • 2
    @user2284570 — It isn't. this question is about *response* headers, not *request* headers. – Quentin Dec 05 '18 at 17:06
  • 1
    While you can't ready _any headers_ of HTML response in JS, you _can_ read `Server-Timing` header, and you can pass arbitrary key-value data through it. See [my answer](https://stackoverflow.com/a/66211531/245966). – jakub.g Feb 15 '21 at 16:20
  • I know this does not answer the question, but could help someone nonetheless. In some situations, where you control the page content and have access to the header data on a server, you could add hidden elements with the desired information. – Charles L. Feb 02 '22 at 18:42

18 Answers18

418

It's not possible to read the current headers. You could make another request to the same URL and read its headers, but there is no guarantee that the headers are exactly equal to the current.


Use the following JavaScript code to get all the HTTP headers by performing a get request:

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
Randy
  • 9,419
  • 5
  • 39
  • 56
Raja
  • 4,373
  • 1
  • 14
  • 2
  • 60
    Saeed, maybe not best for the question author.. I guess it's because it does not access the headers of loaded resource, but makes a new request.. obviously he knows the best, what the best answer is, and made it himself – mykhal Jul 28 '11 at 10:22
  • 1
    I would consider flagging this so that a moderator can mark correctly. Answers the problem, as stated. – thesmart Dec 28 '11 at 04:41
  • 21
    Depending on what header you are after you may want to use the 'HEAD' verb. – scottrudy Mar 01 '12 at 22:39
  • I believe cookies headers are omitted. – Olivier Lalonde Apr 25 '13 at 21:28
  • can you change response header to make browser act in certain way – Muhammad Umer Jul 10 '13 at 18:30
  • 19
    Making a new request will only work if the response values you need are guaranteed to be identical from one request to the next. It will depend on your application, so your mileage with an approach like this will vary. – keparo Aug 17 '13 at 02:21
  • 6
    This hack might work in some scenarios, but it won't work at all if the page containing the script was generated in response to a POST request, and it doesn't help if you're trying to determine whether the server encountered an error (HTTP 5XX) while processing the original request. – claymation Oct 23 '14 at 12:04
  • 1
    There's also `GetResponseHeader('headerName')` if you're only interested in the value of a single header, which I think is the more common use-case. – BlueRaja - Danny Pflughoeft Jan 14 '15 at 16:16
  • 10
    This answer is horribly wrong. The correct answer is "it's not possible". Or to fit this answer "It's not possible, but here's a hack to attempt to simulate it which may or may not work at all for you". – Jan Sep 04 '15 at 16:37
  • 1
    I've seen people asking for clarification on this and related questions...*why* can't the browser access the current page headers? Is there some browser spec somewhere that says "no", and maybe explains reasoning? – dstelow Jun 07 '18 at 22:26
  • how to get client header? – Rajesh N Nov 23 '22 at 14:45
  • source={{ uri: `http://192.168.1.8:3000?${new URLSearchParams({id:'1' }).toString()}`, headers: { Authorization: "Basic xxxxxx", }, }} here how to get Authorization? – Rajesh N Nov 23 '22 at 14:47
342

Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been repeatedly asked, too, because some people would like to get the actual response headers of the original page request without issuing another one.


For AJAX Requests:

If an HTTP request is made over AJAX, it is possible to get the response headers with the getAllResponseHeaders() method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the fetchSimilarHeaders() function below. Note that this is a work-around to the problem that won't be reliable for some applications.

myXMLHttpRequest.getAllResponseHeaders();

This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.


Getting header values from the Initial Page Request:

This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the current page (i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.

The following are a few suggestions for getting around that problem.


1. Requests on Resources which are largely static

If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.

function fetchSimilarHeaders (callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE) {
            //
            // The following headers may often be similar
            // to those of the original page request...
            //
            if (callback && typeof callback === 'function') {
                callback(request.getAllResponseHeaders());
            }
        }
    };

    //
    // Re-request the same page (document.location)
    // We hope to get the same or similar response headers to those which 
    // came with the current page, but we have no guarantee.
    // Since we are only after the headers, a HEAD request may be sufficient.
    //
    request.open('HEAD', document.location, true);
    request.send(null);
}

This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.


2. Make Inferences

There are some BOM properties (Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g. navigator.userAgent is set to the value of the HTTP User-Agent header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.


3. Stash them

If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.

Community
  • 1
  • 1
keparo
  • 33,450
  • 13
  • 60
  • 66
  • 2
    How Google detect it as like I explained here: http://stackoverflow.com/questions/7191242/how-can-i-get-and-parse-accept-header-to-get-language-at-javascript – kamaci Aug 25 '11 at 13:50
  • RE update: ajax requests were a standard part of web development way back in 2008 as well -_- – BlueRaja - Danny Pflughoeft Feb 03 '12 at 22:02
  • 5
    BOM stands for "Browser Object Model", for those wondering. See http://stackoverflow.com/questions/2213594/whats-the-difference-between-the-browser-object-model-and-the-document-object-m for some background. – Myrne Stol Mar 28 '13 at 18:47
  • 2
    3) you could stash them in the http cookie header, too. Then you wouldn't need to change the document markup. – skibulk Nov 26 '14 at 02:51
  • There is a simple way to access the response header elements such as the link element: use document example here: https://gist.github.com/FunThomas424242/ebde1e4fdb7fe4a4056d#file-gistfile1-html – Huluvu424242 May 24 '15 at 16:21
  • If your page is rendered using html templates and you control the server code, you can stash the variables into a hidden div that javascript could read into a variable.
    {{ myvar}}
    – intotecho Feb 16 '16 at 21:14
  • @Huluvu424242's URL throws 404 – Kumar Aug 12 '20 at 03:53
  • @Kumar - thanks for the hint. I have changed my user for deployments. So the link is now: https://gist.github.com/Huluvu424242/ebde1e4fdb7fe4a4056d#file-gistfile1-html – Huluvu424242 Aug 25 '20 at 08:50
  • Just add to this. You can do this now with the fetch() function - supported in chrome, edge and firefox. https://stevemiller.dev/2019/getting-response-headers-with-javascript-fetch/ – sproketboy Nov 19 '20 at 13:46
  • One very useful bit of info is "document.lastModified" which is derived from the Date, Age, and/or the "Last-Modified" headers. I too thought I needed a general API to access all headers, but it turns out this one variable answers exactly the need I wanted satisfied. – Jaredo Mills Feb 11 '23 at 03:12
31

Using XmlHttpRequest you can pull up the current page and then examine the http headers of the response.

Best case is to just do a HEAD request and then examine the headers.

For some examples of doing this have a look at http://www.jibbering.com/2002/4/httprequest.html

Just my 2 cents.

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
Allain Lalonde
  • 91,574
  • 70
  • 187
  • 238
31

A solution with Service Workers

Service workers are able to access network information, which includes headers. The good part is that it works on any kind of request, not just XMLHttpRequest.

How it works:

  1. Add a service worker on your website.
  2. Watch every request that's being sent.
  3. Make the service worker fetch the request with the respondWith function.
  4. When the response arrives, read the headers.
  5. Send the headers from the service worker to the page with the postMessage function.

Working example:

Service workers are a bit complicated to understand, so I've built a small library that does all this. It is available on github: https://github.com/gmetais/sw-get-headers.

Limitations:

  • the website needs to be on HTTPS
  • the browser needs to support the Service Workers API
  • the same-domain/cross-domain policies are in action, just like on XMLHttpRequest
Gaël Métais
  • 804
  • 7
  • 7
  • Two major downsides... WKWebView does not support it on safari 14, the latest. The other issue is there is a bright blue button on Chrome Incognito that also disables Service Workers as most people use them to Store things... not to do critical work. I'm switching to just workers for now... but I seem to be missing headers https://9v1li.csb.app/ – Ray Foss Jul 08 '21 at 09:52
  • That's odd... I wasn't missing headers in the Service Worker. I guess that may have been because I was in a similar origin. I just had to add another header on the server `res.set('Access-Control-Expose-Headers', 'page-size')` https://stackoverflow.com/a/45608476/370238 – Ray Foss Jul 08 '21 at 10:11
29

(2021) An answer without additional HTTP call (works everywhere except Safari)

While it's not possible in general to read arbitrary HTTP response headers of the top-level HTML navigation, if you control the server (or middleboxes on the way) and want to expose some info to JavaScript that can't be exposed easily in any other way than via a header:

You may use Server-Timing header to expose arbitrary key-value data, and it will be readable by JavaScript.

(*in supported browsers: Firefox 61, Chrome 65, Edge 79; no IE, no Safari yet and no immediate plans for shipping as of 2021.09; although it may be implemented for same-origin JS one day.)

Example:

server-timing: key;desc="value"
server-timing: key1;desc="value1"
server-timing: key2;desc="value2"
  • or use its compact version where you expose multiple pieces of data in one header, comma-separated.
server-timing: key1;desc="value1", key2;desc="value2"

Example of how Wikipedia uses this header to expose info about cache hit/miss:

Usage of server-timing response header on Wikipedia

Code example (need to account for lack of browser support in Safari and IE):

if (window.performance && performance.getEntriesByType) { // avoid error in Safari 10, IE9- and other old browsers
    let navTiming = performance.getEntriesByType('navigation')
    if (navTiming.length > 0) { // still not supported as of Safari 14...
        let serverTiming = navTiming[0].serverTiming
        if (serverTiming && serverTiming.length > 0) {
            for (let i=0; i<serverTiming.length; i++) {
                console.log(`${serverTiming[i].name} = ${serverTiming[i].description}`)
            }
        }
    }
}

This logs cache = hit-front in supported browsers.

Notes:

  • as mentioned on MDN, the API is only supported over HTTPS
  • if your JS is served from another domain, you have to add Timing-Allow-Origin response header to make the data readable to JS (Timing-Allow-Origin: * or Timing-Allow-Origin: https://www.example.com)
  • Server-Timing headers support also dur(header) field, readable as duration on JS side, but it's optional and defaults to 0 in JS if not passed
  • regarding Safari support: see bug 1 and bug 2 and bug 3
  • You can read more on server-timing in this blog post
  • Note that performance entries buffers might get cleaned by JS on the page (via an API call), or by the browser, if the page issues too many calls for subresources. For that reason, you should capture the data as soon as possible, and/or use PerformanceObserver API instead. See the blog post for details.
jakub.g
  • 38,512
  • 12
  • 92
  • 130
22

Another way to send header information to JavaScript would be through cookies. The server can extract whatever data it needs from the request headers and send them back inside a Set-Cookie response header — and cookies can be read in JavaScript. As keparo says, though, it's best to do this for just one or two headers, rather than for all of them.

savetheclocktower
  • 1,443
  • 7
  • 12
  • 2
    This approach still requires that you control the server for your JS. No matter how you communicate that info, your code has suddenly been made uncacheable. Why not just make an API for that specific request to avoid corrupting the request for the original asset? – MST Jul 04 '16 at 17:00
  • @MST in my case I have full control of the proxy's but the files are entirely statically deployed. Nginx makes changing headers trivial. – Ray Foss Jul 08 '21 at 09:56
17

For those looking for a way to parse all HTTP headers into an object that can be accessed as a dictionary headers["content-type"], I've created a function parseHttpHeaders:

function parseHttpHeaders(httpHeaders) {
    return httpHeaders.split("\n")
     .map(x=>x.split(/: */,2))
     .filter(x=>x[0])
     .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
}

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = parseHttpHeaders(req.getAllResponseHeaders());
// Now we can do:  headers["content-type"]
Diego
  • 18,035
  • 5
  • 62
  • 66
  • 1
    This always gives me "access has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." How can I know if the headers allow iframe or not? – mesqueeb Apr 08 '21 at 23:24
9

You can't access the http headers, but some of the information provided in them is available in the DOM. For example, if you want to see the http referer (sic), use document.referrer. There may be others like this for other http headers. Try googling the specific thing you want, like "http referer javascript".

I know this should be obvious, but I kept searching for stuff like "http headers javascript" when all I really wanted was the referer, and didn't get any useful results. I don't know how I didn't realize I could make a more specific query.

David Winiecki
  • 4,093
  • 2
  • 37
  • 39
6

Like many people I've been digging the net with no real answer :(

I've nevertheless find out a bypass that could help others. In my case I fully control my web server. In fact it is part of my application (see end reference). It is easy for me to add a script to my http response. I modified my httpd server to inject a small script within every html pages. I only push a extra 'js script' line right after my header construction, that set an existing variable from my document within my browser [I choose location], but any other option is possible. While my server is written in nodejs, I've no doubt that the same technique can be use from PHP or others.

  case ".html":
    response.setHeader("Content-Type", "text/html");
    response.write ("<script>location['GPSD_HTTP_AJAX']=true</script>")
    // process the real contend of my page

Now every html pages loaded from my server, have this script executed by the browser at reception. I can then easily check from JavaScript if the variable exist or not. In my usecase I need to know if I should use JSON or JSON-P profile to avoid CORS issue, but the same technique can be used for other purposes [ie: choose in between development/production server, get from server a REST/API key, etc ....]

On the browser you just need to check variable directly from JavaScript as in my example, where I use it to select my Json/JQuery profile

 // Select direct Ajax/Json profile if using GpsdTracking/HttpAjax server otherwise use JsonP
  var corsbypass = true;  
  if (location['GPSD_HTTP_AJAX']) corsbypass = false;

  if (corsbypass) { // Json & html served from two different web servers
    var gpsdApi = "http://localhost:4080/geojson.rest?jsoncallback=?";
  } else { // Json & html served from same web server [no ?jsoncallback=]
    var gpsdApi = "geojson.rest?";
  }
  var gpsdRqt = 
      {key   :123456789 // user authentication key
      ,cmd   :'list'    // rest command
      ,group :'all'     // group to retreive
      ,round : true     // ask server to round numbers
   };
   $.getJSON(gpsdApi,gpsdRqt, DevListCB);

For who ever would like to check my code: https://www.npmjs.org/package/gpsdtracking

Fulup
  • 545
  • 3
  • 14
6

Allain Lalonde's link made my day. Just adding some simple working html code here.
Works with any reasonable browser since ages plus IE9+ and Presto-Opera 12.

<!DOCTYPE html>
<title>(XHR) Show all response headers</title>

<h1>All Response Headers with XHR</h1>
<script>
 var X= new XMLHttpRequest();
 X.open("HEAD", location);
 X.send();
 X.onload= function() { 
   document.body.appendChild(document.createElement("pre")).textContent= X.getAllResponseHeaders();
 }
</script>

Note: You get headers of a second request, the result may differ from the initial request.


Another way
is the more modern fetch() API
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
Per caniuse.com it's supported by Firefox 40, Chrome 42, Edge 14, Safari 11
Working example code:
<!DOCTYPE html>
<title>fetch() all Response Headers</title>

<h1>All Response Headers with fetch()</h1>
<script>
 var x= "";
 if(window.fetch)
    fetch(location, {method:'HEAD'})
    .then(function(r) {
       r.headers.forEach(
          function(Value, Header) { x= x + Header + "\n" + Value + "\n\n"; }
       );
    })
    .then(function() {
       document.body.appendChild(document.createElement("pre")).textContent= x;
    });
 else
   document.write("This does not work in your browser - no support for fetch API");
</script>
j.j.
  • 1,914
  • 15
  • 12
5

If we're talking about Request headers, you can create your own headers when doing XmlHttpRequests.

var request = new XMLHttpRequest();
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.open("GET", path, true);
request.send(null);
user4020527
  • 1
  • 8
  • 20
Leo
  • 2,860
  • 3
  • 24
  • 21
  • you will not be able to modify request header in mozilla for security reasons. http://mxr.mozilla.org/mozilla1.8.0/source/extensions/xmlextras/base/src/nsXMLHttpRequest.cpp#1637 – user121196 Aug 12 '09 at 20:07
  • 1
    You must call open() before using the setRequestHeader() method. https://developer.mozilla.org/en/XMLHttpRequest#setRequestHeader\(\) – XP1 Aug 09 '11 at 10:00
  • 1
    Access, in the original question, is about getting headers, not setting headers. – Timo Tijhof Feb 12 '16 at 15:32
4

To get the headers as an object which is handier (improvement of Raja's answer):

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
headers = headers.split(/\n|\r|\r\n/g).reduce(function(a, b) {
    if (b.length) {
        var [ key, value ] = b.split(': ');
        a[key] = value;
    }
    return a;
}, {});
shaedrich
  • 5,457
  • 3
  • 26
  • 42
  • 1
    What does `/\n|\r|\r\n/g` mean? Edit: i found the / /g is for all occurrences of either \n, \r or \r\n – LetsGoBrandon Jul 14 '22 at 10:07
  • 2
    @LetsGoBrandon This RegExp replaces line breaks. Different OS use different ways to denote line breaks. This RegExp makes sure, it can be either of them so all can be matched no matter the OS. – shaedrich Jul 14 '22 at 10:11
3

I've just tested, and this works for me using Chrome Version 28.0.1500.95.

I was needing to download a file and read the file name. The file name is in the header so I did the following:

var xhr = new XMLHttpRequest(); 
xhr.open('POST', url, true); 
xhr.responseType = "blob";
xhr.onreadystatechange = function () { 
    if (xhr.readyState == 4) {
        success(xhr.response); // the function to proccess the response

        console.log("++++++ reading headers ++++++++");
        var headers = xhr.getAllResponseHeaders();
        console.log(headers);
        console.log("++++++ reading headers end ++++++++");

    }
};

Output:

Date: Fri, 16 Aug 2013 16:21:33 GMT
Content-Disposition: attachment;filename=testFileName.doc
Content-Length: 20
Server: Apache-Coyote/1.1
Content-Type: application/octet-stream
mkj
  • 2,761
  • 5
  • 24
  • 28
rushmore
  • 147
  • 1
  • 8
3

This is my script to get all the response headers:

var url = "< URL >";

var req = new XMLHttpRequest();
req.open('HEAD', url, false);
req.send(null);
var headers = req.getAllResponseHeaders();

//Show alert with response headers.
alert(headers);

Having as a result the response headers.

enter image description here

This is a comparison test using Hurl.it:

enter image description here

Jorgesys
  • 124,308
  • 23
  • 334
  • 268
2

Using mootools, you can use this.xhr.getAllResponseHeaders()

shaedrich
  • 5,457
  • 3
  • 26
  • 42
-1

This is an old question. Not sure when support became more broad, but getAllResponseHeaders() and getResponseHeader() appear to now be fairly standard: http://www.w3schools.com/xml/dom_http.asp

Wilt
  • 41,477
  • 12
  • 152
  • 203
dlo
  • 1,580
  • 15
  • 24
  • 54
    getAllResponseHeaders() and getResponseHeader() are methods of the the XMLHttpRequest object. I.e. for ajax requests. You can't use those methods to view headers of the initial page - which is what I think the original question was really asking. – asgeo1 Apr 17 '11 at 22:08
-1

As has already been mentioned, if you control the server side then it should be possible to send the initial request headers back to the client in the initial response.

In Express, for example, the following works:

app.get('/somepage', (req, res) => { res.render('somepage.hbs', {headers: req.headers}); }) The headers are then available within the template, so could be hidden visually but included in the markup and read by clientside javascript.

Ollie Williams
  • 1,996
  • 3
  • 25
  • 41
-2

I think the question went in the wrong way, If you want to take the Request header from JQuery/JavaScript the answer is simply No. The other solutions is create a aspx page or jsp page then we can easily access the request header. Take all the request in aspx page and put into a session/cookies then you can access the cookies in JavaScript page..

Santhosh N
  • 62
  • 4
  • 2
    The question is asking about reading the **response** headers. It mentions the request headers only in the context of the possibly related question. – Quentin Dec 05 '18 at 17:05