Get HTTP request headers of request

any idea how i can get all information of HTTP request headers of request , cloudfalre doesn’t provide much information :thinking:

Log them on your origin or use a Worker to log them - those are the only two options unless you have Enterprise to use Logpush/Instant Logs.

2 Likes

any way to use the worker for that ?

This is what i’m using in a Worker to return the HTTP request headers in JSON format:

addEventListener("fetch", event => {
  
  let requestHeaders = [...event.request.headers]
  let createHeaderManifest = (cb) => {
  let headerArray = []
for(let i = 0; i < requestHeaders.length; i++){
  let headerObj = {
  'name' : requestHeaders[i][0],
  'value' : requestHeaders[i][1],
}

headerArray.push(headerObj);
if(i == ( requestHeaders.length - 1 )){
  cb(JSON.stringify({'requestHeaders':headerArray}))
}
}
}
createHeaderManifest( data => {
 const json = data;
 return event.respondWith(
 new Response(json, {
headers: {
"content-type": "application/json;charset=UTF-8",
}
})
)
})
})

Put that in a Worker on an endpoint like ‘/info’. Then use a browser extension for JSON prettifying :slight_smile:

2 Likes

There’s a new method you can use that’ll shorten this down to just return Response.json(json) - which makes it so much nicer to deal with JSON haha Add `Response.json` static method by lucacasonato · Pull Request #1392 · whatwg/fetch · GitHub

Let’s you do something as concise as this:

export default {
	async fetch(request) {
		const headers = [];

		for (var pair of request.headers.entries()) {
			headers.push({
				name: pair[0],
				value: pair[1],
			});
		}

		return Response.json(headers);
	},
};
1 Like

but how i can get the logs of that requests ??
where i can find them ?
sorry i have not used workers before

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.