Skip to content

CloudFlare workers Response.type workaround #159

@jimmed

Description

@jimmed

I've been using wretch for a few years now, and I absolutely adore it!

Recently I started using it in the CloudFlare Workers runtime. I noticed that when handling a non-ok response, wretch attempts to access the response's type property.

wretch/src/resolver.ts

Lines 52 to 54 in c1fc7a6

if (response.type === "opaque") {
throw err
}

Unfortunately, CF's Response implementation defines a getter for type, which throws an error, as they don't implement this field (given it's a server runtime, not a browser).

https://github.com/cloudflare/miniflare/blob/9d96aaa66aa48eb1107c86fe24cbfd444249533c/packages/core/src/standards/http.ts#L637-L639

To work around this, I wrote a small middleware:

wretch().middlewares([
  (next) => async (url, opts) => {
    const response = await next(url, opts);
    try {
      Reflect.get(response, "type", response);
    } catch (error) {
      Object.defineProperty(response, "type", {
        get: () => "default",
      });
    }
    return response;
  },
])

I'm not sure whether you would prefer to add this to wretch's documentation somewhere, or change wretch's error handling logic such that it catches these errors from CF.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions