Tip: Request and Response Headers

Published

The other day I was working on some unit tests for a minimal Cloudflare Worker that would redirect the incoming request while forwarding along some of the original request headers. I setup a test to call the worker's fetch handler with a new Request that had some headers provided:

1let request = new Request('https://something.com', {
2 headers: {
3 'x-foo': 'bar',
4 'x-baz': 'qux'
5 }
6});
1let request = new Request('https://something.com', {
2 headers: {
3 'x-foo': 'bar',
4 'x-baz': 'qux'
5 }
6});

I then called the worker's fetch handler with this request:

1let response = await worker.fetch(request);
1let response = await worker.fetch(request);

However, the headers weren't propagating into the request that my worker's fetch handler was seeing - since I was calling the method directly I figured it had to be something with the runtime that I was writing the tests within (in this case, Bun).

I did some sleuthing online and found this issue. The creator of the issue noted something about this being baked into the spec for new Request and new Response objects, and that they don't "hydrate" from a HeadersInit object.

To instead make it work, I had to write my test like this:

1let request = new Request('https://something.com');
2request.headers.set('x-foo', 'bar');
3request.headers.set('x-baz', 'qux');
4
5let response = await worker.fetch(request);
1let request = new Request('https://something.com');
2request.headers.set('x-foo', 'bar');
3request.headers.set('x-baz', 'qux');
4
5let response = await worker.fetch(request);