Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 22 additions & 21 deletions products/workers/src/content/examples/logging-headers.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ Use the spread operator if you need to quickly stringify a Headers object:
let requestHeaders = JSON.stringify([...request.headers])
```

Or use ES2019 `Object.fromEntries` to convert it to an object:

```js
let requestHeaders = Object.fromEntries(request.headers)
```

### The problem

When debugging Worker scripts, we often want to examine the headers on a request or response. A common pitfall is to try to log headers to the developer console via code like this:
Expand All @@ -64,7 +70,7 @@ The reason this happens is because [Headers](https://developer.mozilla.org/en-US

Headers objects are iterable, however, which we can take advantage of to develop a couple quick one-liners for debug-printing headers.

## Pass headers through a Map
### Pass headers through a Map

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.

Expand All @@ -91,30 +97,25 @@ let requestHeaders = JSON.stringify([...request.headers], null, 2)
console.log(`Request headers: ${requestHeaders}`)
```

### Convert headers into an object with Object.fromEntries (ES2019)

[ES2019 provides `Object.fromEntries`](https://github.com/tc39/proposal-object-from-entries), so it's just a simple call to convert the headers into an object:

```js
let requestHeaders = JSON.stringify(Object.fromEntries(request.headers), null, 2)
console.log(`Request headers: ${requestHeaders}`)
```

This results in something like:

```js
Request headers: [
[
"accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
],
[
"accept-encoding",
"gzip"
],
[
"accept-language",
"en-US,en;q=0.9"
],
[
"cf-ipcountry",
"US"
],
Request headers: {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"accept-encoding": "gzip",
"accept-language": "en-US,en;q=0.9",
"cf-ipcountry": "US",
// ...
]
}"
```

While not as elegant as object literal syntax, this is certainly readable and useful for debugging purposes.

</ContentColumn>