Re: [whatwg/fetch] Use case for Headers getAll (#973)

@domenic Again, I agree with you if you were to look at the usage of `Headers` in browsers in isolation. Consider this scenario in a "service worker @ edge" environment like Deno Deploy or Cloudflare Workers, that allow you to rewrite requests/responses in a server environment before they get forwarded onto the client. This example adds a `Content-Security-Policy` header to all proxied requests:

```js
addEventListener("fetch", (e) => {
  e.respondWith(handler(e.req));
});

async function handler(req) {
  const resp = await fetch(req); // forward the original request to the origin server
  const headers = new Headers(resp.headers); // clone the headers object to strip off the `immutable` header guard
  headers.set("Content-Security-Policy", "default-src 'none'; style-src 'self'; script-src 'self'");
  return new Response(resp.body, { status: resp.status, headers });
}
```

On the surface it looks like this should just work for all cases. It is only 4 lines after all. The problem is that it doesn't work. If the origin server responds with some `set-cookie` headers (which is pretty likely, as cookies are widely used), then the header cloning will mangle these `set-cookie` headers by cloning them. Instead of responding to the client with multiple `set-cookie` headers, the client will now receive a single malformed cookie header.

With the current API as specified, there is no way to solve this. You can not just `headers.get("set-cookie").split(", ")`, because `,` are valid characters in set-cookie headers.

As you can see, with this proposed change of altering the iterator, this code now works as expected. It solves a use-case which was previously **not possible** to solve with just features from the standard. Because of this we already have two incompatible extensions from Deno and Cloudflare that allow users to do this anyway. This is not sustainable - we need WHATWG to engage with other implementers that are not browser vendors - otherwise the ecosystem will diverge. This is not something that is in anyone's best interest IMO.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/973#issuecomment-961221410

Received on Thursday, 4 November 2021 16:41:38 UTC