Search code examples
javascripthttphttp-headers

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


I want to capture the HTTP request header fields, primarily the Referer and User-Agent, within my client-side JavaScript. How may I access them?


Google Analytics manages to get the data via JavaScript that they have you embed in you pages, so it is definitely possible.

Related:
Accessing the web page's HTTP Headers in JavaScript


Solution

  • If you want to access referrer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly.

    To retrieve the referrer, use document.referrer.
    To access the user-agent, use navigator.userAgent.

    As others have indicated, the HTTP headers are not available, but you specifically asked about the referer and user-agent, which are available via Javascript.