ResendProvider cannot send on Workers: unbound `fetch` stored as an instance property throws "Illegal invocation"

Open Beginner friendly
#1,099 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

@lane711 is already working on this.

Since Oct 27, 2026.

  • #1145 by @lane711 — open

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
72/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
cloud, typescript
Domain
backend

Research direction

The bug is in the constructor of ResendProvider in src/services/email/providers/resend.ts, which stores the global fetch unbound in this.fetchImpl, and send() then calls it as a method. Check src/services/email/providers/sendgrid.ts for the same pattern, and compare CfGraphqlClient in the same package, which already wraps fetch. Done means send() reaches the HTTP call without an "Illegal invocation" error, which you can confirm with a unit test that stubs the global fetch or with wrangler dev.

Written by the indexing model from the issue text.

Description

area: email bug priority: P1

Summary

ResendProvider (and SendGridProvider) store the global fetch as an instance property and then invoke it as a method. On Cloudflare Workers that calls fetch with this bound to the provider instance instead of the global scope, and the runtime rejects it:

TypeError: Illegal invocation: function called with incorrect `this` reference.

Since Workers is the only platform SonicJS targets, the Resend provider can never send an email.

Root cause

src/services/email/providers/resend.ts:

constructor(options = {}) {
  this.apiKey = options.apiKey;
  this.endpoint = options.endpoint ?? RESEND_ENDPOINT;
  this.fetchImpl = options.fetchImpl ?? fetch;      // ← unbound
}

async send(message) {
  const res = await this.fetchImpl(this.endpoint, { ... });   // ← this = provider
}

initEmailService never passes fetchImpl, so the ?? fetch default is always what runs in practice:

provider = resolveEmailProvider({ providerName: "resend", env: { ...env, RESEND_API_KEY: resendKey } });

resolveEmailProvider → buildNamed(name, env, options.fetchImpl) → new ResendProvider({ apiKey, fetchImpl: undefined }).

src/services/email/providers/sendgrid.ts has the identical pattern and is presumably affected the same way (not verified — no SendGrid account to test with).

Notably CfGraphqlClient in the same package already does it correctly:

constructor(zoneId, apiToken, fetchImpl = (input, init) => fetch(input, init)) {

Reproduction

Minimal, on wrangler dev (same workerd runtime as production):

export default {
  async fetch(): Promise<Response> {
    const out: Record<string, unknown> = {}

    // the core's pattern
    try {
      const holder = { fetchImpl: fetch }
      await holder.fetchImpl('https://api.resend.com/emails', { method: 'POST' })
      out.corePattern = 'no error (unexpected)'
    } catch (e) {
      out.corePattern = String(e)
    }

    // wrapped
    try {
      const holder = { fetchImpl: (i: RequestInfo, init?: RequestInit) => fetch(i, init) }
      const res = await holder.fetchImpl('https://api.resend.com/emails', { method: 'POST' })
      out.wrapped = `HTTP ${res.status}`
    } catch (e) {
      out.wrapped = String(e)
    }

    return Response.json(out)
  },
}

Result:

{
  "corePattern": "TypeError: Illegal invocation: function called with incorrect `this` reference. ...",
  "wrapped": "HTTP 401"
}

End to end against the real provider, with a deliberately invalid key:

core ResendProvider  → TypeError: Illegal invocation
wrapped equivalent   → Resend responded 401: {"statusCode":401,"name":"validation_error","message":"API key is invalid"}

The 401 is the point: the request actually reaches Resend once fetch keeps its correct this.

Suggested fix

Same shape already used by CfGraphqlClient:

this.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));

or bind it: ?? fetch.bind(globalThis). Worth applying to SendGridProvider in the same pass.

User-facing impact

The admin test-send surfaces this as a bare ❌ Illegal invocation: ... with a link to the Cloudflare error docs. Nothing points at the email provider, so it reads as a platform problem rather than a library one.

This also compounds #1098 (email settings are read from a plugins table that no longer exists in v3): a user who works around that one, by setting RESEND_API_KEY or config.email, then hits this second wall immediately.

Workaround

Supply your own provider through config.email.provider. resolveEmailProvider returns it as-is (if (options.provider) return options.provider), bypassing the built-in construction entirely:

class BoundResendProvider {
  readonly name = 'resend'
  isConfigured() { return !!apiKey }
  async send(message) {
    const res = await fetch('https://api.resend.com/emails', {
      method: 'POST',
      headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({
        from: message.from, to: message.to, subject: message.subject,
        html: message.html, text: message.text, reply_to: message.replyTo,
      }),
    })
    // ...
  }
}

One wrinkle worth documenting: config is built at module load, when env is not available, so the API key has to be read at send time (we capture it from a beforeAuth middleware).

Environment

@sonicjs-cms/core 3.0.0-beta.28
Runtime Cloudflare Workers (production) and wrangler dev
wrangler 4.131.2
node 22.22.3
Dominant language
TypeScript
Stars
1.8k
Forks
219
Avg merge
2d 21h
Merged PRs (30d)
67

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from SonicJs-Org/sonicjs

All issues in SonicJs-Org/sonicjs

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.