gja / cloudflare-worker-local

Run a Cloudflare Worker Locally

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Example worker modifies a Response object

sodabrew opened this issue · comments

The example worker modifies the Response object from a fetch call. This is not allowed in Workers. There isn't a clean way that I know of to deeply freeze an object in Javascript, but at a minimum this example is invalid:

addEventListener("fetch", e => {
  e.respondWith(fetchAndAddHeader(e.request));
});

async function fetchAndAddHeader(request) {
  const response = await fetch(request);

  if (response.status === 200) {
    response.headers.set("Foo", "Bar"); // <--  KABOOM
  } else {
    response.headers.set("Foo", "Not Bar"); // <-- KABLAMO
  }

  return response;
}

Thanks for this. I didn't notice that. I'll update the example later tonight.

Thanks! Yeah, this change should do the trick. This has bitten me a few times in my own unit test suite for Workers. Haven't figured out a way to model this immutability in a test harness yet.