Logging headers to console
Examine the contents of a Headers object by logging to console with a Map.
Use a Map
if you need to log a Headers
object to the console:
Use the spread
operator if you need to quickly stringify a Headers
object:
Use Object.fromEntries
to convert the headers to an object:
When debugging Workers, examine the headers on a request or response. A common mistake is to try to log headers to the developer console via code like this:
Or this:
Both attempts result in what appears to be an empty object — the string "{}"
— even though calling request.headers.has("Your-Header-Name")
might return true. This is the same behavior that browsers implement.
The reason this happens is because Headers ↗ objects do not store headers in enumerable JavaScript properties, so the developer console and JSON stringifier do not know how to read the names and values of the headers. It is not actually an empty object, but rather an opaque object.
Headers
objects are iterable, which you can take advantage of to develop a couple of quick one-liners for debug-printing headers.
The first common idiom for making Headers console.log()
-friendly is to construct a Map
object from the Headers
object and log the Map
object.
This works because:
-
Map
objects can be constructed from iterables, likeHeaders
. -
The
Map
object does store its entries in enumerable JavaScript properties, so the developer console can see into it.
The Map
approach works for calls to console.log()
. If you need to stringify your headers, you will discover that stringifying a Map
yields nothing more than [object Map]
.
Even though a Map
stores its data in enumerable properties, those properties are Symbol ↗-keyed. Because of this, JSON.stringify()
will ignore Symbol-keyed properties ↗ and you will receive an empty {}
.
Instead, you can take advantage of the iterability of the Headers
object in a new way by applying the spread operator ↗ (...
) to it.
ES2019 provides Object.fromEntries
↗ which is a call to convert the headers into an object:
This results in something like: