Sveltekit (@auth/sveltekit) / Cloudflare Workers
Environment
System:
OS: macOS 14.6.1
CPU: (8) x64 Intel(R) Core(TM) i7-1068NG7 CPU @ 2.30GHz
Memory: 29.28 MB / 32.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 22.2.0 - /usr/local/bin/node
Yarn: 1.22.15 - /usr/local/bin/yarn
npm: 10.7.0 - /usr/local/bin/npm
pnpm: 6.11.0 - /usr/local/bin/pnpm
Browsers:
Chrome: 129.0.6668.90
Safari: 17.6
npmPackages:
@auth/sveltekit: ^1.6.0 => 1.6.0
Reproduction URL
https://github.com/pragmatic-recursion/auth-bug
Describe the issue
Running on Cloudflare Workers, not Pages! Works locally.
Server error
There is a problem with the server configuration.
Check the server logs for more information.
{
"$cloudflare": {
"truncated": false,
"event": {
"request": {
"url": "https://one.pragmatic-recursion.workers.dev/auth/callback/github?code=62d6a29f6a2e303b9fba",
"method": "GET",
"path": "/auth/callback/github"
}
},
"scriptName": "one",
"eventType": "fetch",
"scriptVersion": {
"id": "6c4e96d9-0a8b-4ff0-89e7-a7b056292571"
},
"$metadata": {
"requestId": "8cf4d7f4fde4b36d",
"id": "01J9NMRD9E8N8G90RMFDYBQF7F",
"type": "cf-worker",
"error": "\u001b[31m[auth][cause]\u001b[0m: TypeError: Illegal invocation: function called with incorrect `this` reference. See https://developers.cloudflare.com/workers/observability/errors/#illegal-invocation-errors for details.\n at _worker.js:7568:47\n at authenticatedRequest (_worker.js:4949:44)",
"errorPattern": "\u001b[<NUM>m[auth][cause]\u001b[<NUM>m: TypeError: Illegal invocation: function called with incorrect `this` reference. See <URL>#illegal-invocation-errors for details.\n at <URL>:<NUM>\n at authenticate",
"messagePattern": "\u001b[<NUM>m[auth][cause]\u001b[<NUM>m: TypeError: Illegal invocation: function called with incorrect `this` reference. See <URL>#illegal-invocation-errors for details.\n at <URL>:<NUM>\n at authenticate"
}
},
"level": "error",
"message": "\u001b[31m[auth][cause]\u001b[0m: TypeError: Illegal invocation: function called with incorrect `this` reference. See https://developers.cloudflare.com/workers/observability/errors/#illegal-invocation-errors for details.\n at _worker.js:7568:47\n at authenticatedRequest (_worker.js:4949:44)"
}
How to reproduce
-
Install Svelte https://developers.cloudflare.com/workers/frameworks/framework-guides/svelte/ npm create cloudflare@latest my-svelte-app -- --framework=svelte --experimental
-
Install @auth/sveltekit https://authjs.dev/reference/sveltekit npm install @auth/sveltekit
-
Add GitHub as a Provider
-
Deploy to Cloudflare Worker (Free)
It works locally but not when deployed
Expected behavior
Should be logged in
I encountered this as well. Reverting to
"@auth/core": "^0.35.0",
"@auth/sveltekit": "1.5.3",
works as expected. Maybe this is an issue with the new customFetch that @balazsorban44 added recently?
Here's the more-useful trace I get running locally with the newer releases:
TypeError: Illegal invocation: function called with incorrect `this` reference. See https://developers.cloudflare.com/workers/observability/errors/#illegal-invocation-errors for details.
at Object.apply
(file:///Users/jakemoves/projects/mixtape-project/mixtape/.wrangler/tmp/bundle-YxKLIk/checked-fetch.js:28:18)
at Object.apply
(file:///Users/jakemoves/projects/mixtape-project/mixtape/.wrangler/tmp/bundle-ul11C8/checked-fetch.js:28:18)
at null.<anonymous>
(file:///Users/jakemoves/projects/mixtape-project/mixtape/node_modules/.pnpm/@[email protected]/node_modules/@auth/core/lib/actions/callback/oauth/callback.js:65:52)
at authenticatedRequest
... and the linked docs from Cloudflare at https://developers.cloudflare.com/workers/observability/errors/#illegal-invocation-errors
@jakemoves You're a life saver. I can finally ship. 🥹
Hmm. Unless you override customFetch, (which you really shouldn't in 99+% of the cases) we fall back to the globally available fetch
https://github.com/nextauthjs/next-auth/blob/57fe1e1e9befab929d4034ba89713d7b364872e3/packages/core/src/lib/utils/custom-fetch.ts#L33
No clue why this would break Cloudflare yet...
This happened to me too, not using @auth/sveletekit. This is running locally in Miniflare (Cloudflare simulator) using wrangler.
I logged all of the values in the custom fetch function in case something there rings a bell:
provider = {
id: 'github',
name: 'GitHub',
type: 'oauth',
authorization: { url: [URL], request: undefined, conform: undefined },
token: { url: [URL] },
userinfo: {
url: [URL],
request: [AsyncFunction: request],
conform: undefined
},
profile: [Function: profile],
style: { bg: '#24292f', text: '#fff' },
clientId: '...',
clientSecret: '...',
issuer: undefined,
signinUrl: 'http://localhost:8787/auth/signin/github',
callbackUrl: 'http://localhost:8787/auth/callback/github',
redirectProxyUrl: undefined,
checks: [ 'pkce' ],
account: [Function: defaultAccount],
[Symbol(custom-fetch)]: undefined
}
o.customFetch = Symbol()
customFetch = Symbol(custom-fetch)
fetch = [Function: fetch]
X [ERROR] [auth][error] CallbackRouteError: Read more at https://errors.authjs.dev#callbackrouteerror
[auth][cause]: TypeError: Illegal invocation: function called with
incorrect `this` reference. See
https://developers.cloudflare.com/workers/observability/errors/#illegal-invocation-errors
for details.
at Object.apply
(file:///C:/.../.wrangler/tmp/bundle-ZruFbV/checked-fetch.js:28:18)
at null.<anonymous>
(file:///C:/.../node_modules/.pnpm/@[email protected]/node_modules/@auth/core/lib/actions/callback/oauth/callback.js:116:52)
at authenticatedRequest
(file:///C:/.../node_modules/.pnpm/[email protected]/node_modules/oauth4webapi/src/index.ts:3094:37)
at async tokenEndpointRequest
(file:///C:/.../node_modules/.pnpm/[email protected]/node_modules/oauth4webapi/src/index.ts:3136:20)
[auth][details]: {
"provider": "github"
}
jakemoves
This works perfectly. Appreciate it!
same here, can confirm the issue and downgrading resolving it.
We're seeing a related but slightly different manifestation of this issue in standard Vite SSR (not Cloudflare Workers).
The error occurs during Vite's SSR module evaluation:
SyntaxError: [vite] The requested module '@auth/core' does not provide an export named 'customFetch'
at analyzeImportedModDifference (vite/dist/node/chunks/dep-Cyk9bIUq.js:52042:15)
Our version compatibility findings:
- Works:
@auth/[email protected]with@auth/[email protected] - Fails:
-
@auth/[email protected]with@auth/[email protected](missing export error) -
@auth/[email protected]with@auth/[email protected](version mismatch)
-
The fact that this manifests both in Cloudflare Workers (as an illegal invocation) and in standard Vite SSR (as a missing export) suggests there might be a broader issue with how customFetch is being exported and consumed.
Technical details:
- In
@auth/[email protected],customFetchis defined inlib/symbols.jsand re-exported inindex.js - The type definitions correctly show the export
- The error occurs specifically during SSR initialization
- The application never reaches client-side execution due to the SSR failure
Environment:
- Vite: 5.4.9
- pnpm 9.12.2
Hello,
I believe this issue might be related to the one discussed here, so I’d like to provide additional context.
I’m encountering an issue with Next.js App Router using NextAuth v5 for OAuth authentication (GitHub and Google providers). On Cloudflare Pages, the callback after login results in an Internal Server Error. However, it works perfectly on Vercel and in a local environment running next dev.
To debug this, I tried running npx wrangler pages dev to emulate the Cloudflare Pages environment locally. When attempting GitHub authentication, the following error appeared, and the callback request resulted in an Internal Server Error:
log :
[wrangler:inf] Ready on http://localhost:8788
[wrangler:inf] GET / 200 OK (143ms)
[wrangler:inf] GET / 200 OK (14ms)
[wrangler:inf] GET /favicon.ico 304 Not Modified (15ms)
[wrangler:inf] POST / 303 See Other (27ms)
✘ [ERROR] TypeError: Illegal invocation: function called with incorrect `this` reference. See https://developers.cloudflare.com/workers/observability/errors/#illegal-invocation-errors for details.
at K.waitUntil
(file:///Users/test/Documents/products/auth-app/.vercel/output/static/_worker.js/__next-on-pages-dist__/functions/auth/[...nextauth].func.js:2:826)
at Ne.handler
(file:///Users/test/Documents/products/auth-app/.vercel/output/static/_worker.js/__next-on-pages-dist__/functions/auth/[...nextauth].func.js:2:23931)
at async et
(file:///Users/test/Documents/products/auth-app/.vercel/output/static/_worker.js/__next-on-pages-dist__/functions/auth/[...nextauth].func.js:2:4302)
at async Module.<anonymous>
(file:///Users/test/Documents/products/auth-app/.vercel/output/static/_worker.js/__next-on-pages-dist__/functions/auth/[...nextauth].func.js:8:3805)
at async E
(file:///Users/test/Documents/products/auth-app/.vercel/output/static/_worker.js/index.js:40:14667)
at async ke
(file:///Users/test/Documents/products/auth-app/.vercel/output/static/_worker.js/index.js:40:25857)
at async jsonError
(file:///Users/test/Documents/products/auth-app/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts:22:10)
at async drainBody
(file:///Users/test/Documents/products/auth-app/node_modules/wrangler/templates/middleware/middleware-ensure-req-body-drained.ts:5:10)
[wrangler:inf] GET /auth/callback/github 500 Internal Server Error (1074ms)
From the logs, it seems to relate to a TypeError: Illegal invocation, which might be caused by incorrect context binding in the this reference during execution.
Could this issue be related to compatibility between NextAuth v5 and Cloudflare Workers? I’d appreciate any insights or guidance on how to address this issue.
Thank you in advance!
package.json :
"dependencies": {
"@cloudflare/next-on-pages": "^1.13.6",
"next": "^15.0.3",
"next-auth": "^5.0.0-beta.25",
"react": "latest",
"react-dom": "latest",
"wrangler": "^3.91.0"
},
"devDependencies": {
"@types/node": "latest",
"@types/react": "latest",
"@types/react-dom": "latest",
"typescript": "latest"
}
same error next-auth
TypeError: Illegal invocation: function called with incorrect \`this\` reference.
I'm also experiencing the same issue. When using NextAuth with Cloudflare,
However, after updating @cloudflare/next-on-pages to the recently released version 1.13.7, everything worked fine.
TypeError: Illegal invocation: function called with incorrect \`this\` reference.I'm also experiencing the same issue. When using NextAuth with Cloudflare,
However, after updating
@cloudflare/next-on-pagesto the recently released version 1.13.7, everything worked fine.
@jj811208 Working fine too! You saved my life.
@muuuuminn @jj811208 - just to clarify, is this fix (@cloudflare/[email protected]) only relevant to next.js projects, or also svelte(kit) on CF Pages?
i cannot for the life of me get the basic nextauth sveltekit demo working on CF Pages....
@rawwerks
I haven't been able to confirm whether this issue is resolved on Svelte(Kit).
I could only verify it for Next.js.
Sorry I couldn't be of more help.
thanks! it's too bad the next auth team seems to have abandoned svelte...
@rawwerks I just deployed a brand new Sveltekit to CF Workers Static Assets using @auth/sveltekit": "^1.7.4, and had no issues. Just putting it out there. I only did Github and Discord providers this time. Not sure if that makes a difference.