This API returns the HTTP request headers your browser sent, as JSON.
GET /api/headers
To use this API, embed it using a <script> element and pass a callback function name via the
callback query parameter. This guarantees cross-origin compatibility without relying on CORS fetch
requests.
<!-- Define your callback function -->
<script>
function processHeaders(data) {
if (data.error) {
console.error(data.error);
return;
}
console.log(data.headers["accept-language"]);
}
</script>
<!-- Inject the script tag to call the API -->
<script src="https://<your-domain>/api/headers?callback=processHeaders"></script>
The response is a JSON object containing the headers and a brief note.
{
"headers": {
"accept": "text/html,application/xhtml+xml,...",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9,de;q=0.8",
"host": "us-central1-myproject.cloudfunctions.net",
"user-agent": "Mozilla/5.0 ..."
},
"note": "These are the HTTP request headers sent by your browser for this request."
}
By passing the callback parameter, the API automatically wraps the response in a function call
(JSONP). The endpoint also returns Access-Control-Allow-Origin: * if you prefer to make standard
fetch() requests.
<script>
request, not the original page navigation. Most headers (Accept-Language, User-Agent,
DNT) will be identical, but some (Accept, Referer) will differ because
the browser constructs a fresh resource fetch.
If you prefer a nicer API to fetch and cache headers dynamically across your application via JSONP, you can use this simple class:
class RequestHeaders {
constructor(endpoint = "/api/headers") {
this.endpoint = endpoint;
this._promise = null;
}
fetch() {
if (!this._promise) {
this._promise = new Promise((resolve, reject) => {
// Generate a unique callback name
const callbackName = 'headersCallback_' + Math.round(1000000 * Math.random());
// Setup the global listener
window[callbackName] = function(data) {
delete window[callbackName];
resolve(data.headers);
};
// Inject the script element
const script = document.createElement('script');
const url = new URL(this.endpoint, window.location.origin);
url.searchParams.set('callback', callbackName);
script.src = url.toString();
script.onerror = () => reject(new Error('Failed to load headers via script'));
document.body.appendChild(script);
});
}
return this._promise;
}
async get(name) {
const headers = await this.fetch();
return headers[name.toLowerCase()] ?? null;
}
}
// Usage (same site):
const rh = new RequestHeaders("/api/headers");
const lang = await rh.get("Accept-Language");
// Usage (cross-origin):
const rh = new RequestHeaders("https://<your-domain>/api/headers");
const lang = await rh.get("Accept-Language");