ResendProvider cannot send on Workers: unbound `fetch` stored as an instance property throws "Illegal invocation"
Maintainers usually reply within 1 day
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
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
- Ships a Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from SonicJs-Org/sonicjs
-
bug(admin/users): server error returns bare alert HTML causing black-shape visual artifactPossibly taken @lane711 claimed this today. Openbug
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
SonicJs-Org/sonicjs#1211 ·
Maintainers usually reply within 1 day
-
area: api bug priority: P2
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
SonicJs-Org/sonicjs#1200 ·
Maintainers usually reply within 1 day
-
Email plugin settings are never read: loadDbEmailSettings queries a v2 `plugins` table that does not exist in v3Possibly taken @lane711 claimed this 23 days ago. Openarea: email bug priority: P1
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
SonicJs-Org/sonicjs#1098 ·
Maintainers usually reply within 1 day
-
area: documentation bug documentation priority: P2
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
SonicJs-Org/sonicjs#1012 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
SonicJs-Org/sonicjs#471 ·
Maintainers usually reply within 1 day
All issues in SonicJs-Org/sonicjs
Similar issues
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
AloisSeckar/elrh-cosca#36 ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 73/100
cursor/community-plugins#572 ·
Maintainers usually reply within 1 day
-
[Plugin] calendarOpen
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
MUKE-coder/grit#228 ·
-
bug status:needs-triage
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
dongdongbh/Mindwtr#1587 ·
Maintainers usually reply within 1 day