Logging and Using Headers
How to log the headers received and use them.
When debugging Edge Functions, a common mistake is to try to log headers to the developer console via code like this:
Both attempts will give as output the string "{}"
, even though retrieving the value using request.headers.get("Your-Header-Name")
will indeed give you the correct value. This behavior mirrors that of browsers.
The reason behind this behavior is that Headers objects don't store headers in JavaScript properties that can be enumerated. As a result, neither the developer console nor the JSON stringifier can properly interpret the names and values of the headers. Essentially, it's not an empty object, but rather an opaque one.
However, Headers
objects are iterable. You can utilize this feature to craft a couple of succinct one-liners for debugging and printing headers.
Convert headers into an object with Object.fromEntries:
You can use Object.fromEntries
which is a call to convert the headers into an object:
This results in something like: