[GH-ISSUE #6613] Upgrade from 1.3 to 1.4: Error runWithRequestState on cloudflare workers #19203

Closed
opened 2026-04-15 18:01:32 -05:00 by GiteaMirror · 33 comments
Owner

Originally created by @tnkuehne on GitHub (Dec 8, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/6613

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Follow the setup guide for SvelteKit https://www.better-auth.com/docs/integrations/svelte-kit. This worked perfectly deployed on cloudflare workers (node compat enabled "compatibility_date": "2025-06-12" and "compatibility_flags": ["nodejs_compat"] with version 1.3
  2. Upgrade to 1.4
  3. Call await auth.api.signInSSO
const res = await auth.api.signInSSO({
    body: {
        email,
        callbackURL: redirectTo,
    },
});

Throws error

No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.
    at getCurrentRequestState (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:41:20)
    at async set (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:63:5)
    at async generateState (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-auth@1.4.5_@sveltejs+kit@2.49.1_@opentelemetry+api@1.9.0_@sveltejs+vite-plugin-s_2117d6321a543e35ae24707332b8d2bc/node_modules/better-auth/dist/utils-db7gNqd-.mjs:28:2)
    at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-OZuMhX/_worker.js:116425:26)
    at async internalHandler (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-call@1.1.4_zod@4.1.13/node_modules/better-call/src/endpoint.ts:503:20)
    at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-OZuMhX/_worker.js:141196:26)
    at async trySSO (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/entries/pages/login/_page.server.ts.js:66:11)
    at async default (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/entries/pages/login/_page.server.ts.js:101:17)
    at async fn (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/index.js:646:19)
    at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-OZuMhX/_worker.js:512753:14)

Current vs. Expected behavior

Before upgrading to 1.4, it was working, and now it's broken.

What version of Better Auth are you using?

1.4.5

System info

{
  "system": {
    "platform": "linux",
    "arch": "x64",
    "version": "#36~24.04.1-Ubuntu SMP PREEMPT_DYNAMIC Wed Oct 15 15:45:17 UTC 2",
    "release": "6.14.0-36-generic",
    "cpuCount": 16,
    "cpuModel": "AMD Ryzen 7 PRO 5850U with Radeon Graphics",
    "totalMemory": "27.23 GB",
    "freeMemory": "9.15 GB"
  },
  "node": {
    "version": "v22.19.0",
    "env": "development"
  },
  "packageManager": {
    "name": "pnpm",
    "version": "10.23.0"
  },
  "frameworks": [
    {
      "name": "svelte",
      "version": "^5.45.6"
    },
    {
      "name": "@sveltejs/kit",
      "version": "^2.49.1"
    }
  ],
  "databases": [
    {
      "name": "drizzle",
      "version": "^0.45.0"
    },
    {
      "name": "@neondatabase/serverless",
      "version": "^1.0.2"
    }
  ],
  "betterAuth": {
    "version": "^1.4.5",
    "config": {
      "baseURL": "http://localhost:8787",
      "account": {
        "accountLinking": {
          "enabled": true,
          "allowDifferentEmails": true
        }
      },
      "socialProviders": {
        "microsoft": {
          "clientId": "[REDACTED]",
          "clientSecret": "[REDACTED]",
          "tenantId": "common",
          "authority": "https://login.microsoftonline.com",
          "prompt": "select_account"
        }
      },
      "plugins": [
        {
          "name": "email-otp",
          "config": {
            "id": "email-otp",
            "endpoints": {},
            "hooks": {
              "after": [
                {}
              ]
            },
            "$ERROR_CODES": {
              "OTP_EXPIRED": "OTP expired",
              "INVALID_OTP": "Invalid OTP",
              "TOO_MANY_ATTEMPTS": "Too many attempts"
            },
            "rateLimit": [
              {
                "window": 60,
                "max": 3
              },
              {
                "window": 60,
                "max": 3
              },
              {
                "window": 60,
                "max": 3
              },
              {
                "window": 60,
                "max": 3
              }
            ]
          }
        },
        {
          "name": "admin",
          "config": {
            "id": "admin",
            "hooks": {
              "after": [
                {}
              ]
            },
            "endpoints": {},
            "$ERROR_CODES": {
              "FAILED_TO_CREATE_USER": "Failed to create user",
              "USER_ALREADY_EXISTS": "User already exists.",
              "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL": "User already exists. Use another email.",
              "YOU_CANNOT_BAN_YOURSELF": "You cannot ban yourself",
              "YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE": "You are not allowed to change users role",
              "YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS": "You are not allowed to create users",
              "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS": "You are not allowed to list users",
              "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS": "You are not allowed to list users sessions",
              "YOU_ARE_NOT_ALLOWED_TO_BAN_USERS": "You are not allowed to ban users",
              "YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS": "You are not allowed to impersonate users",
              "YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS": "You are not allowed to revoke users sessions",
              "YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS": "You are not allowed to delete users",
              "YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD": "[REDACTED]",
              "BANNED_USER": "You have been banned from this application",
              "YOU_ARE_NOT_ALLOWED_TO_GET_USER": "You are not allowed to get user",
              "NO_DATA_TO_UPDATE": "No data to update",
              "YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS": "You are not allowed to update users",
              "YOU_CANNOT_REMOVE_YOURSELF": "You cannot remove yourself",
              "YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE": "You are not allowed to set a non-existent role value"
            },
            "schema": {
              "user": {
                "fields": {
                  "role": {
                    "type": "string",
                    "required": false,
                    "input": false
                  },
                  "banned": {
                    "type": "boolean",
                    "defaultValue": false,
                    "required": false,
                    "input": false
                  },
                  "banReason": {
                    "type": "string",
                    "required": false,
                    "input": false
                  },
                  "banExpires": {
                    "type": "date",
                    "required": false,
                    "input": false
                  }
                }
              },
              "session": {
                "fields": {
                  "impersonatedBy": {
                    "type": "string",
                    "required": false
                  }
                }
              }
            }
          }
        },
        {
          "name": "organization",
          "config": {
            "id": "organization",
            "endpoints": {},
            "schema": {
              "organization": {
                "fields": {
                  "name": {
                    "type": "string",
                    "required": true,
                    "sortable": true
                  },
                  "slug": {
                    "type": "string",
                    "required": true,
                    "unique": true,
                    "sortable": true
                  },
                  "logo": {
                    "type": "string",
                    "required": false
                  },
                  "createdAt": {
                    "type": "date",
                    "required": true
                  },
                  "metadata": {
                    "type": "string",
                    "required": false
                  }
                }
              },
              "member": {
                "fields": {
                  "organizationId": {
                    "type": "string",
                    "required": true,
                    "references": {
                      "model": "organization",
                      "field": "id"
                    },
                    "index": true
                  },
                  "userId": {
                    "type": "string",
                    "required": true,
                    "references": {
                      "model": "user",
                      "field": "id"
                    },
                    "index": true
                  },
                  "role": {
                    "type": "string",
                    "required": true,
                    "sortable": true,
                    "defaultValue": "member"
                  },
                  "createdAt": {
                    "type": "date",
                    "required": true
                  }
                }
              },
              "invitation": {
                "fields": {
                  "organizationId": {
                    "type": "string",
                    "required": true,
                    "references": {
                      "model": "organization",
                      "field": "id"
                    },
                    "index": true
                  },
                  "email": {
                    "type": "string",
                    "required": true,
                    "sortable": true,
                    "index": true
                  },
                  "role": {
                    "type": "string",
                    "required": false,
                    "sortable": true
                  },
                  "status": {
                    "type": "string",
                    "required": true,
                    "sortable": true,
                    "defaultValue": "pending"
                  },
                  "expiresAt": {
                    "type": "date",
                    "required": true
                  },
                  "createdAt": {
                    "type": "date",
                    "required": true
                  },
                  "inviterId": {
                    "type": "string",
                    "references": {
                      "model": "user",
                      "field": "id"
                    },
                    "required": true
                  }
                }
              },
              "session": {
                "fields": {
                  "activeOrganizationId": {
                    "type": "string",
                    "required": false
                  }
                }
              }
            },
            "$Infer": {
              "Organization": {},
              "Invitation": {},
              "Member": {},
              "Team": {},
              "TeamMember": {},
              "ActiveOrganization": {}
            },
            "$ERROR_CODES": {
              "YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION": "You are not allowed to create a new organization",
              "YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS": "You have reached the maximum number of organizations",
              "ORGANIZATION_ALREADY_EXISTS": "Organization already exists",
              "ORGANIZATION_SLUG_ALREADY_TAKEN": "Organization slug already taken",
              "ORGANIZATION_NOT_FOUND": "Organization not found",
              "USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION": "User is not a member of the organization",
              "YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION": "You are not allowed to update this organization",
              "YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION": "You are not allowed to delete this organization",
              "NO_ACTIVE_ORGANIZATION": "No active organization",
              "USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION": "User is already a member of this organization",
              "MEMBER_NOT_FOUND": "Member not found",
              "ROLE_NOT_FOUND": "Role not found",
              "YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM": "You are not allowed to create a new team",
              "TEAM_ALREADY_EXISTS": "Team already exists",
              "TEAM_NOT_FOUND": "Team not found",
              "YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER": "You cannot leave the organization as the only owner",
              "YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER": "You cannot leave the organization without an owner",
              "YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER": "You are not allowed to delete this member",
              "YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION": "You are not allowed to invite users to this organization",
              "USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION": "User is already invited to this organization",
              "INVITATION_NOT_FOUND": "Invitation not found",
              "YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION": "You are not the recipient of the invitation",
              "EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION": "Email verification required before accepting or rejecting invitation",
              "YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION": "You are not allowed to cancel this invitation",
              "INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION": "Inviter is no longer a member of the organization",
              "YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE": "You are not allowed to invite a user with this role",
              "FAILED_TO_RETRIEVE_INVITATION": "Failed to retrieve invitation",
              "YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS": "You have reached the maximum number of teams",
              "UNABLE_TO_REMOVE_LAST_TEAM": "Unable to remove last team",
              "YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER": "You are not allowed to update this member",
              "ORGANIZATION_MEMBERSHIP_LIMIT_REACHED": "Organization membership limit reached",
              "YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION": "You are not allowed to create teams in this organization",
              "YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION": "You are not allowed to delete teams in this organization",
              "YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM": "You are not allowed to update this team",
              "YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM": "You are not allowed to delete this team",
              "INVITATION_LIMIT_REACHED": "Invitation limit reached",
              "TEAM_MEMBER_LIMIT_REACHED": "Team member limit reached",
              "USER_IS_NOT_A_MEMBER_OF_THE_TEAM": "User is not a member of the team",
              "YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM": "You are not allowed to list the members of this team",
              "YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM": "You do not have an active team",
              "YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER": "You are not allowed to create a new member",
              "YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER": "You are not allowed to remove a team member",
              "YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION": "You are not allowed to access this organization as an owner",
              "YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION": "You are not a member of this organization",
              "MISSING_AC_INSTANCE": "Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",
              "YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE": "You must be in an organization to create a role",
              "YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE": "You are not allowed to create a role",
              "YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE": "You are not allowed to update a role",
              "YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE": "You are not allowed to delete a role",
              "YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE": "You are not allowed to read a role",
              "YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE": "You are not allowed to list a role",
              "YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE": "You are not allowed to get a role",
              "TOO_MANY_ROLES": "This organization has too many roles",
              "INVALID_RESOURCE": "The provided permission includes an invalid resource",
              "ROLE_NAME_IS_ALREADY_TAKEN": "That role name is already taken",
              "CANNOT_DELETE_A_PRE_DEFINED_ROLE": "Cannot delete a pre-defined role"
            },
            "options": {
              "ac": {
                "statements": {
                  "organization": [
                    "update",
                    "delete"
                  ],
                  "member": [
                    "create",
                    "update",
                    "delete"
                  ],
                  "invitation": [
                    "create",
                    "cancel"
                  ],
                  "team": [
                    "create",
                    "update",
                    "delete"
                  ],
                  "ac": [
                    "create",
                    "read",
                    "update",
                    "delete"
                  ],
                  "onboarding": [
                    "create",
                    "read",
                    "update",
                    "delete"
                  ],
                  "management": [
                    "create",
                    "read",
                    "update",
                    "delete"
                  ]
                }
              },
              "roles": {
                "owner": {
                  "statements": {
                    "onboarding": [
                      "create",
                      "read",
                      "update",
                      "delete"
                    ],
                    "management": [
                      "create",
                      "read",
                      "update",
                      "delete"
                    ],
                    "organization": [
                      "update",
                      "delete"
                    ],
                    "member": [
                      "create",
                      "update",
                      "delete"
                    ],
                    "invitation": [
                      "create",
                      "cancel"
                    ],
                    "team": [
                      "create",
                      "update",
                      "delete"
                    ],
                    "ac": [
                      "create",
                      "read",
                      "update",
                      "delete"
                    ]
                  }
                },
                "admin": {
                  "statements": {
                    "onboarding": [
                      "create",
                      "read",
                      "update",
                      "delete"
                    ],
                    "management": [
                      "create",
                      "read",
                      "update",
                      "delete"
                    ],
                    "organization": [
                      "update"
                    ],
                    "invitation": [
                      "create",
                      "cancel"
                    ],
                    "member": [
                      "create",
                      "update",
                      "delete"
                    ],
                    "team": [
                      "create",
                      "update",
                      "delete"
                    ],
                    "ac": [
                      "create",
                      "read",
                      "update",
                      "delete"
                    ]
                  }
                },
                "member": {
                  "statements": {
                    "onboarding": [
                      "read"
                    ],
                    "organization": [],
                    "member": [],
                    "invitation": [],
                    "team": [],
                    "ac": [
                      "read"
                    ]
                  }
                },
                "supervisor": {
                  "statements": {
                    "onboarding": [
                      "create",
                      "read",
                      "update",
                      "delete"
                    ],
                    "organization": [],
                    "member": [],
                    "invitation": [],
                    "team": [],
                    "ac": [
                      "read"
                    ]
                  }
                },
                "manager": {
                  "statements": {
                    "onboarding": [
                      "create",
                      "read",
                      "update",
                      "delete"
                    ],
                    "management": [
                      "create",
                      "read",
                      "update",
                      "delete"
                    ],
                    "organization": [],
                    "member": [],
                    "invitation": [],
                    "team": [],
                    "ac": [
                      "read"
                    ]
                  }
                }
              }
            }
          }
        },
        {
          "name": "sso",
          "config": {
            "id": "sso",
            "endpoints": {},
            "schema": {
              "ssoProvider": {
                "modelName": "ssoProvider",
                "fields": {
                  "issuer": {
                    "type": "string",
                    "required": true,
                    "fieldName": "issuer"
                  },
                  "oidcConfig": {
                    "type": "string",
                    "required": false,
                    "fieldName": "oidcConfig"
                  },
                  "samlConfig": {
                    "type": "string",
                    "required": false,
                    "fieldName": "samlConfig"
                  },
                  "userId": {
                    "type": "string",
                    "references": {
                      "model": "user",
                      "field": "id"
                    },
                    "fieldName": "userId"
                  },
                  "providerId": {
                    "type": "string",
                    "required": true,
                    "unique": true,
                    "fieldName": "providerId"
                  },
                  "organizationId": {
                    "type": "string",
                    "required": false,
                    "fieldName": "organizationId"
                  },
                  "domain": {
                    "type": "string",
                    "required": true,
                    "fieldName": "domain"
                  }
                }
              }
            }
          }
        },
        {
          "name": "passkey",
          "config": {
            "id": "passkey",
            "endpoints": {},
            "schema": {
              "passkey": {
                "fields": {
                  "name": {
                    "type": "string",
                    "required": false
                  },
                  "publicKey": {
                    "type": "string",
                    "required": true
                  },
                  "userId": {
                    "type": "string",
                    "references": {
                      "model": "user",
                      "field": "id"
                    },
                    "required": true,
                    "index": true
                  },
                  "credentialID": {
                    "type": "string",
                    "required": true,
                    "index": true
                  },
                  "counter": {
                    "type": "number",
                    "required": true
                  },
                  "deviceType": {
                    "type": "string",
                    "required": true
                  },
                  "backedUp": {
                    "type": "boolean",
                    "required": true
                  },
                  "transports": {
                    "type": "string",
                    "required": false
                  },
                  "createdAt": {
                    "type": "date",
                    "required": false
                  },
                  "aaguid": {
                    "type": "string",
                    "required": false
                  }
                }
              }
            },
            "$ERROR_CODES": {
              "CHALLENGE_NOT_FOUND": "Challenge not found",
              "YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY": "You are not allowed to register this passkey",
              "FAILED_TO_VERIFY_REGISTRATION": "Failed to verify registration",
              "PASSKEY_NOT_FOUND": "Passkey not found",
              "AUTHENTICATION_FAILED": "Authentication failed",
              "UNABLE_TO_CREATE_SESSION": "Unable to create session",
              "FAILED_TO_UPDATE_PASSKEY": "Failed to update passkey"
            }
          }
        },
        {
          "name": "sveltekit-cookies",
          "config": {
            "id": "sveltekit-cookies",
            "hooks": {
              "after": [
                {}
              ]
            }
          }
        }
      ],
      "telemetry": {
        "enabled": false
      },
      "advanced": {}
    }
  }
}

Which area(s) are affected? (Select all that apply)

Backend

Auth config (if applicable)

import { dev } from "$app/environment";
import { getRequestEvent } from "$app/server";
import { env } from "$env/dynamic/private";
import { BETTER_AUTH_URL } from "$env/static/private";
import { ac, roles } from "$lib/permissions";
import { db } from "$lib/server/db";
import {
    sendOTPEmail,
    sendOTPSignInEmail,
    sendOTPVerificationEmail,
    sendOrganizationInvitationEmail,
} from "$lib/server/email";
import { sso } from "@better-auth/sso";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import {
    admin as adminPlugin,
    emailOTP,
    organization,
} from "better-auth/plugins";
import { passkey } from "@better-auth/passkey";
import { sveltekitCookies } from "better-auth/svelte-kit";

const MICROSOFT_CLIENT_ID = env.MICROSOFT_CLIENT_ID;
const MICROSOFT_CLIENT_SECRET = env.MICROSOFT_CLIENT_SECRET;
if (!MICROSOFT_CLIENT_ID || !MICROSOFT_CLIENT_SECRET) {
    throw new Error(
        "Missing required environment variable: MICROSOFT_CLIENT_ID or MICROSOFT_CLIENT_SECRET",
    );
}

export const auth = betterAuth({
    baseURL: BETTER_AUTH_URL,
    database: drizzleAdapter(db, {
        provider: "pg",
    }),
    account: {
        accountLinking: {
            enabled: true,
            allowDifferentEmails: true,
        },
    },
    socialProviders: {
        microsoft: {
            clientId: MICROSOFT_CLIENT_ID,
            clientSecret: MICROSOFT_CLIENT_SECRET,
            tenantId: "common",
            authority: "https://login.microsoftonline.com",
            prompt: "select_account",
        },
    },
    plugins: [
        emailOTP({
            async sendVerificationOTP({ email, otp, type }) {
                if (dev) {
                    console.log(`OTP ${otp} sent to ${email}`);
                    return Promise.resolve();
                }
                if (type === "sign-in") {
                    await sendOTPSignInEmail(otp, email);
                } else if (type === "email-verification") {
                    await sendOTPVerificationEmail(otp, email);
                } else {
                    await sendOTPEmail(otp, email);
                }
            },
            disableSignUp: true,
        }),
        adminPlugin(),
        organization({
            ac,
            roles,
            async sendInvitationEmail(data) {
                const inviteLink = `${BETTER_AUTH_URL}/accept-invitation/${data.id}`;
                if (dev) {
                    console.log(`Invite link: ${inviteLink}`);
                    return Promise.resolve();
                }
                await sendOrganizationInvitationEmail(
                    data.email,
                    data.inviter.user.name,
                    data.inviter.user.email,
                    data.organization.name,
                    inviteLink,
                );
            },
        }),
        sso({
            organizationProvisioning: {
                disabled: false,
                defaultRole: "member",
            },
        }),
        passkey({
            rpID: dev ? "localhost" : new URL(BETTER_AUTH_URL).hostname,
            rpName: "mendra AI",
            origin: dev ? "http://localhost:5173" : BETTER_AUTH_URL,
        }),
        sveltekitCookies(getRequestEvent),
    ],
    telemetry: {
        enabled: false,
    },
    advanced: dev
        ? {}
        : {
              ipAddress: {
                  ipAddressHeaders: ["cf-connecting-ip"],
              },
          },
});

Additional context

No response

Originally created by @tnkuehne on GitHub (Dec 8, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/6613 ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. Follow the setup guide for SvelteKit https://www.better-auth.com/docs/integrations/svelte-kit. This worked perfectly deployed on cloudflare workers (node compat enabled `"compatibility_date": "2025-06-12"` and `"compatibility_flags": ["nodejs_compat"]` with version 1.3 2. Upgrade to 1.4 3. Call `await auth.api.signInSSO` ```ts const res = await auth.api.signInSSO({ body: { email, callbackURL: redirectTo, }, }); ``` Throws error ```console No request state found. Please make sure you are calling this function within a `runWithRequestState` callback. at getCurrentRequestState (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:41:20) at async set (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:63:5) at async generateState (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-auth@1.4.5_@sveltejs+kit@2.49.1_@opentelemetry+api@1.9.0_@sveltejs+vite-plugin-s_2117d6321a543e35ae24707332b8d2bc/node_modules/better-auth/dist/utils-db7gNqd-.mjs:28:2) at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-OZuMhX/_worker.js:116425:26) at async internalHandler (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-call@1.1.4_zod@4.1.13/node_modules/better-call/src/endpoint.ts:503:20) at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-OZuMhX/_worker.js:141196:26) at async trySSO (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/entries/pages/login/_page.server.ts.js:66:11) at async default (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/entries/pages/login/_page.server.ts.js:101:17) at async fn (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/index.js:646:19) at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-OZuMhX/_worker.js:512753:14) ``` ### Current vs. Expected behavior Before upgrading to 1.4, it was working, and now it's broken. ### What version of Better Auth are you using? 1.4.5 ### System info ```bash { "system": { "platform": "linux", "arch": "x64", "version": "#36~24.04.1-Ubuntu SMP PREEMPT_DYNAMIC Wed Oct 15 15:45:17 UTC 2", "release": "6.14.0-36-generic", "cpuCount": 16, "cpuModel": "AMD Ryzen 7 PRO 5850U with Radeon Graphics", "totalMemory": "27.23 GB", "freeMemory": "9.15 GB" }, "node": { "version": "v22.19.0", "env": "development" }, "packageManager": { "name": "pnpm", "version": "10.23.0" }, "frameworks": [ { "name": "svelte", "version": "^5.45.6" }, { "name": "@sveltejs/kit", "version": "^2.49.1" } ], "databases": [ { "name": "drizzle", "version": "^0.45.0" }, { "name": "@neondatabase/serverless", "version": "^1.0.2" } ], "betterAuth": { "version": "^1.4.5", "config": { "baseURL": "http://localhost:8787", "account": { "accountLinking": { "enabled": true, "allowDifferentEmails": true } }, "socialProviders": { "microsoft": { "clientId": "[REDACTED]", "clientSecret": "[REDACTED]", "tenantId": "common", "authority": "https://login.microsoftonline.com", "prompt": "select_account" } }, "plugins": [ { "name": "email-otp", "config": { "id": "email-otp", "endpoints": {}, "hooks": { "after": [ {} ] }, "$ERROR_CODES": { "OTP_EXPIRED": "OTP expired", "INVALID_OTP": "Invalid OTP", "TOO_MANY_ATTEMPTS": "Too many attempts" }, "rateLimit": [ { "window": 60, "max": 3 }, { "window": 60, "max": 3 }, { "window": 60, "max": 3 }, { "window": 60, "max": 3 } ] } }, { "name": "admin", "config": { "id": "admin", "hooks": { "after": [ {} ] }, "endpoints": {}, "$ERROR_CODES": { "FAILED_TO_CREATE_USER": "Failed to create user", "USER_ALREADY_EXISTS": "User already exists.", "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL": "User already exists. Use another email.", "YOU_CANNOT_BAN_YOURSELF": "You cannot ban yourself", "YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE": "You are not allowed to change users role", "YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS": "You are not allowed to create users", "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS": "You are not allowed to list users", "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS": "You are not allowed to list users sessions", "YOU_ARE_NOT_ALLOWED_TO_BAN_USERS": "You are not allowed to ban users", "YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS": "You are not allowed to impersonate users", "YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS": "You are not allowed to revoke users sessions", "YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS": "You are not allowed to delete users", "YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD": "[REDACTED]", "BANNED_USER": "You have been banned from this application", "YOU_ARE_NOT_ALLOWED_TO_GET_USER": "You are not allowed to get user", "NO_DATA_TO_UPDATE": "No data to update", "YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS": "You are not allowed to update users", "YOU_CANNOT_REMOVE_YOURSELF": "You cannot remove yourself", "YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE": "You are not allowed to set a non-existent role value" }, "schema": { "user": { "fields": { "role": { "type": "string", "required": false, "input": false }, "banned": { "type": "boolean", "defaultValue": false, "required": false, "input": false }, "banReason": { "type": "string", "required": false, "input": false }, "banExpires": { "type": "date", "required": false, "input": false } } }, "session": { "fields": { "impersonatedBy": { "type": "string", "required": false } } } } } }, { "name": "organization", "config": { "id": "organization", "endpoints": {}, "schema": { "organization": { "fields": { "name": { "type": "string", "required": true, "sortable": true }, "slug": { "type": "string", "required": true, "unique": true, "sortable": true }, "logo": { "type": "string", "required": false }, "createdAt": { "type": "date", "required": true }, "metadata": { "type": "string", "required": false } } }, "member": { "fields": { "organizationId": { "type": "string", "required": true, "references": { "model": "organization", "field": "id" }, "index": true }, "userId": { "type": "string", "required": true, "references": { "model": "user", "field": "id" }, "index": true }, "role": { "type": "string", "required": true, "sortable": true, "defaultValue": "member" }, "createdAt": { "type": "date", "required": true } } }, "invitation": { "fields": { "organizationId": { "type": "string", "required": true, "references": { "model": "organization", "field": "id" }, "index": true }, "email": { "type": "string", "required": true, "sortable": true, "index": true }, "role": { "type": "string", "required": false, "sortable": true }, "status": { "type": "string", "required": true, "sortable": true, "defaultValue": "pending" }, "expiresAt": { "type": "date", "required": true }, "createdAt": { "type": "date", "required": true }, "inviterId": { "type": "string", "references": { "model": "user", "field": "id" }, "required": true } } }, "session": { "fields": { "activeOrganizationId": { "type": "string", "required": false } } } }, "$Infer": { "Organization": {}, "Invitation": {}, "Member": {}, "Team": {}, "TeamMember": {}, "ActiveOrganization": {} }, "$ERROR_CODES": { "YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION": "You are not allowed to create a new organization", "YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS": "You have reached the maximum number of organizations", "ORGANIZATION_ALREADY_EXISTS": "Organization already exists", "ORGANIZATION_SLUG_ALREADY_TAKEN": "Organization slug already taken", "ORGANIZATION_NOT_FOUND": "Organization not found", "USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION": "User is not a member of the organization", "YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION": "You are not allowed to update this organization", "YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION": "You are not allowed to delete this organization", "NO_ACTIVE_ORGANIZATION": "No active organization", "USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION": "User is already a member of this organization", "MEMBER_NOT_FOUND": "Member not found", "ROLE_NOT_FOUND": "Role not found", "YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM": "You are not allowed to create a new team", "TEAM_ALREADY_EXISTS": "Team already exists", "TEAM_NOT_FOUND": "Team not found", "YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER": "You cannot leave the organization as the only owner", "YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER": "You cannot leave the organization without an owner", "YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER": "You are not allowed to delete this member", "YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION": "You are not allowed to invite users to this organization", "USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION": "User is already invited to this organization", "INVITATION_NOT_FOUND": "Invitation not found", "YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION": "You are not the recipient of the invitation", "EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION": "Email verification required before accepting or rejecting invitation", "YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION": "You are not allowed to cancel this invitation", "INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION": "Inviter is no longer a member of the organization", "YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE": "You are not allowed to invite a user with this role", "FAILED_TO_RETRIEVE_INVITATION": "Failed to retrieve invitation", "YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS": "You have reached the maximum number of teams", "UNABLE_TO_REMOVE_LAST_TEAM": "Unable to remove last team", "YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER": "You are not allowed to update this member", "ORGANIZATION_MEMBERSHIP_LIMIT_REACHED": "Organization membership limit reached", "YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION": "You are not allowed to create teams in this organization", "YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION": "You are not allowed to delete teams in this organization", "YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM": "You are not allowed to update this team", "YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM": "You are not allowed to delete this team", "INVITATION_LIMIT_REACHED": "Invitation limit reached", "TEAM_MEMBER_LIMIT_REACHED": "Team member limit reached", "USER_IS_NOT_A_MEMBER_OF_THE_TEAM": "User is not a member of the team", "YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM": "You are not allowed to list the members of this team", "YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM": "You do not have an active team", "YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER": "You are not allowed to create a new member", "YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER": "You are not allowed to remove a team member", "YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION": "You are not allowed to access this organization as an owner", "YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION": "You are not a member of this organization", "MISSING_AC_INSTANCE": "Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information", "YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE": "You must be in an organization to create a role", "YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE": "You are not allowed to create a role", "YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE": "You are not allowed to update a role", "YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE": "You are not allowed to delete a role", "YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE": "You are not allowed to read a role", "YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE": "You are not allowed to list a role", "YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE": "You are not allowed to get a role", "TOO_MANY_ROLES": "This organization has too many roles", "INVALID_RESOURCE": "The provided permission includes an invalid resource", "ROLE_NAME_IS_ALREADY_TAKEN": "That role name is already taken", "CANNOT_DELETE_A_PRE_DEFINED_ROLE": "Cannot delete a pre-defined role" }, "options": { "ac": { "statements": { "organization": [ "update", "delete" ], "member": [ "create", "update", "delete" ], "invitation": [ "create", "cancel" ], "team": [ "create", "update", "delete" ], "ac": [ "create", "read", "update", "delete" ], "onboarding": [ "create", "read", "update", "delete" ], "management": [ "create", "read", "update", "delete" ] } }, "roles": { "owner": { "statements": { "onboarding": [ "create", "read", "update", "delete" ], "management": [ "create", "read", "update", "delete" ], "organization": [ "update", "delete" ], "member": [ "create", "update", "delete" ], "invitation": [ "create", "cancel" ], "team": [ "create", "update", "delete" ], "ac": [ "create", "read", "update", "delete" ] } }, "admin": { "statements": { "onboarding": [ "create", "read", "update", "delete" ], "management": [ "create", "read", "update", "delete" ], "organization": [ "update" ], "invitation": [ "create", "cancel" ], "member": [ "create", "update", "delete" ], "team": [ "create", "update", "delete" ], "ac": [ "create", "read", "update", "delete" ] } }, "member": { "statements": { "onboarding": [ "read" ], "organization": [], "member": [], "invitation": [], "team": [], "ac": [ "read" ] } }, "supervisor": { "statements": { "onboarding": [ "create", "read", "update", "delete" ], "organization": [], "member": [], "invitation": [], "team": [], "ac": [ "read" ] } }, "manager": { "statements": { "onboarding": [ "create", "read", "update", "delete" ], "management": [ "create", "read", "update", "delete" ], "organization": [], "member": [], "invitation": [], "team": [], "ac": [ "read" ] } } } } } }, { "name": "sso", "config": { "id": "sso", "endpoints": {}, "schema": { "ssoProvider": { "modelName": "ssoProvider", "fields": { "issuer": { "type": "string", "required": true, "fieldName": "issuer" }, "oidcConfig": { "type": "string", "required": false, "fieldName": "oidcConfig" }, "samlConfig": { "type": "string", "required": false, "fieldName": "samlConfig" }, "userId": { "type": "string", "references": { "model": "user", "field": "id" }, "fieldName": "userId" }, "providerId": { "type": "string", "required": true, "unique": true, "fieldName": "providerId" }, "organizationId": { "type": "string", "required": false, "fieldName": "organizationId" }, "domain": { "type": "string", "required": true, "fieldName": "domain" } } } } } }, { "name": "passkey", "config": { "id": "passkey", "endpoints": {}, "schema": { "passkey": { "fields": { "name": { "type": "string", "required": false }, "publicKey": { "type": "string", "required": true }, "userId": { "type": "string", "references": { "model": "user", "field": "id" }, "required": true, "index": true }, "credentialID": { "type": "string", "required": true, "index": true }, "counter": { "type": "number", "required": true }, "deviceType": { "type": "string", "required": true }, "backedUp": { "type": "boolean", "required": true }, "transports": { "type": "string", "required": false }, "createdAt": { "type": "date", "required": false }, "aaguid": { "type": "string", "required": false } } } }, "$ERROR_CODES": { "CHALLENGE_NOT_FOUND": "Challenge not found", "YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY": "You are not allowed to register this passkey", "FAILED_TO_VERIFY_REGISTRATION": "Failed to verify registration", "PASSKEY_NOT_FOUND": "Passkey not found", "AUTHENTICATION_FAILED": "Authentication failed", "UNABLE_TO_CREATE_SESSION": "Unable to create session", "FAILED_TO_UPDATE_PASSKEY": "Failed to update passkey" } } }, { "name": "sveltekit-cookies", "config": { "id": "sveltekit-cookies", "hooks": { "after": [ {} ] } } } ], "telemetry": { "enabled": false }, "advanced": {} } } } ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { dev } from "$app/environment"; import { getRequestEvent } from "$app/server"; import { env } from "$env/dynamic/private"; import { BETTER_AUTH_URL } from "$env/static/private"; import { ac, roles } from "$lib/permissions"; import { db } from "$lib/server/db"; import { sendOTPEmail, sendOTPSignInEmail, sendOTPVerificationEmail, sendOrganizationInvitationEmail, } from "$lib/server/email"; import { sso } from "@better-auth/sso"; import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { admin as adminPlugin, emailOTP, organization, } from "better-auth/plugins"; import { passkey } from "@better-auth/passkey"; import { sveltekitCookies } from "better-auth/svelte-kit"; const MICROSOFT_CLIENT_ID = env.MICROSOFT_CLIENT_ID; const MICROSOFT_CLIENT_SECRET = env.MICROSOFT_CLIENT_SECRET; if (!MICROSOFT_CLIENT_ID || !MICROSOFT_CLIENT_SECRET) { throw new Error( "Missing required environment variable: MICROSOFT_CLIENT_ID or MICROSOFT_CLIENT_SECRET", ); } export const auth = betterAuth({ baseURL: BETTER_AUTH_URL, database: drizzleAdapter(db, { provider: "pg", }), account: { accountLinking: { enabled: true, allowDifferentEmails: true, }, }, socialProviders: { microsoft: { clientId: MICROSOFT_CLIENT_ID, clientSecret: MICROSOFT_CLIENT_SECRET, tenantId: "common", authority: "https://login.microsoftonline.com", prompt: "select_account", }, }, plugins: [ emailOTP({ async sendVerificationOTP({ email, otp, type }) { if (dev) { console.log(`OTP ${otp} sent to ${email}`); return Promise.resolve(); } if (type === "sign-in") { await sendOTPSignInEmail(otp, email); } else if (type === "email-verification") { await sendOTPVerificationEmail(otp, email); } else { await sendOTPEmail(otp, email); } }, disableSignUp: true, }), adminPlugin(), organization({ ac, roles, async sendInvitationEmail(data) { const inviteLink = `${BETTER_AUTH_URL}/accept-invitation/${data.id}`; if (dev) { console.log(`Invite link: ${inviteLink}`); return Promise.resolve(); } await sendOrganizationInvitationEmail( data.email, data.inviter.user.name, data.inviter.user.email, data.organization.name, inviteLink, ); }, }), sso({ organizationProvisioning: { disabled: false, defaultRole: "member", }, }), passkey({ rpID: dev ? "localhost" : new URL(BETTER_AUTH_URL).hostname, rpName: "mendra AI", origin: dev ? "http://localhost:5173" : BETTER_AUTH_URL, }), sveltekitCookies(getRequestEvent), ], telemetry: { enabled: false, }, advanced: dev ? {} : { ipAddress: { ipAddressHeaders: ["cf-connecting-ip"], }, }, }); ``` ### Additional context _No response_
GiteaMirror added the bug label 2026-04-15 18:01:32 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Dec 8, 2025):

This error is due to a breaking change in Better Auth starting from v1.3.23 and made stricter in 1.4: social and SSO sign-in flows (like signInSSO) must now be initiated from the client side using the authClient instance from better-auth/client, not from the server or backend API routes. This is required so the OAuth state parameter and cookies are set correctly in the browser. If you call these endpoints from the server, you'll get missing request state or state mismatch errors, especially in environments like Cloudflare Workers where context propagation is strict details & fix.

To resolve this, move your SSO/social sign-in initiation to the client and use authClient.api.signInSSO instead of calling auth.api.signInSSO on the server. Only the callback endpoints should remain server-handled. Make sure your Cloudflare Worker has the nodejs_compat flag enabled, but the main fix is moving sign-in initiation to the client.

If you need an example or further migration details, let me know!

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other

Chat with Dosu Open in Cursor Join Discord Share on X

<!-- gh-comment-id:3627674694 --> @dosubot[bot] commented on GitHub (Dec 8, 2025): <!-- Answer --> This error is due to a breaking change in Better Auth starting from v1.3.23 and made stricter in 1.4: social and SSO sign-in flows (like `signInSSO`) must now be initiated from the client side using the `authClient` instance from `better-auth/client`, not from the server or backend API routes. This is required so the OAuth state parameter and cookies are set correctly in the browser. If you call these endpoints from the server, you'll get missing request state or state mismatch errors, especially in environments like Cloudflare Workers where context propagation is strict [details & fix](https://github.com/better-auth/better-auth/issues/5055). To resolve this, move your SSO/social sign-in initiation to the client and use `authClient.api.signInSSO` instead of calling `auth.api.signInSSO` on the server. Only the callback endpoints should remain server-handled. Make sure your Cloudflare Worker has the `nodejs_compat` flag enabled, but the main fix is moving sign-in initiation to the client. If you need an example or further migration details, let me know! <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/731f3d19-6199-4ad9-abd2-61f307eeaaa0?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/731f3d19-6199-4ad9-abd2-61f307eeaaa0?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/731f3d19-6199-4ad9-abd2-61f307eeaaa0?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/731f3d19-6199-4ad9-abd2-61f307eeaaa0?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/731f3d19-6199-4ad9-abd2-61f307eeaaa0?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/731f3d19-6199-4ad9-abd2-61f307eeaaa0?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/731f3d19-6199-4ad9-abd2-61f307eeaaa0?feedback_type=other)</sup> [![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Open in Cursor](https://dosu.dev/dosu-in-cursor.svg)](https://cursor.com/link/prompt?text=This%20error%20is%20due%20to%20a%20breaking%20change%20in%20Better%20Auth%20starting%20from%20v1.3.23%20and%20made%20stricter%20in%201.4%3A%20social%20and%20SSO%20sign-in%20flows%20%28like%20%60signInSSO%60%29%20must%20now%20be%20initiated%20from%20the%20client%20side%20using%20the%20%60authClient%60%20instance%20from%20%60better-auth/client%60%2C%20not%20from%20the%20server%20or%20backend%20API%20routes.%20This%20is%20required%20so%20the%20OAuth%20state%20parameter%20and%20cookies%20are%20set%20correctly%20in%20the%20browser.%20If%20you%20call%20these%20endpoints%20from%20the%20server%2C%20you%27ll%20get%20missing%20request%20state%20or%20state%20mismatch%20errors%2C%20especially%20in%20environments%20like%20Cloudflare%20Workers%20where%20context%20propagation%20is%20strict%C2%A0%5Bdetails%20%26%20fix%5D%28https%3A//github.com/better-auth/better-auth/issues/5055%29.%0A%0ATo%20resolve%20this%2C%20move%20your%20SSO/social%20sign-in%20initiation%20to%20the%20client%20and%20use%20%60authClient.api.signInSSO%60%20instead%20of%20calling%20%60auth.api.signInSSO%60%20on%20the%20server.%20Only%20the%20callback%20endpoints%20should%20remain%20server-handled.%20Make%20sure%20your%20Cloudflare%20Worker%20has%20the%20%60nodejs_compat%60%20flag%20enabled%2C%20but%20the%20main%20fix%20is%20moving%20sign-in%20initiation%20to%20the%20client.%0A%0AIf%20you%20need%20an%20example%20or%20further%20migration%20details%2C%20let%20me%20know%21)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/6613)
Author
Owner

@tnkuehne commented on GitHub (Dec 8, 2025):

@dosu

Ok, migrated it to use await authClient.signIn.sso on the client. But I get almost the same error:

✘ [ERROR] 2025-12-08T16:07:31.136Z ERROR [Better Auth]: Error Error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.

      at getCurrentRequestState
  (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:41:20)
      at async set
  (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:63:5)
      at async generateState
  (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-auth@1.4.5_@sveltejs+kit@2.49.1_@opentelemetry+api@1.9.0_@sveltejs+vite-plugin-s_2117d6321a543e35ae24707332b8d2bc/node_modules/better-auth/dist/utils-db7gNqd-.mjs:28:2)
      at null.<anonymous> (async
  file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:116425:26)
      at async internalHandler
  (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-call@1.1.4_zod@4.1.13/node_modules/better-call/src/endpoint.ts:503:20)
      at null.<anonymous> (async
  file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:141196:26)
      at async processRequest
  (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/chunks/adapter-factory-HF3JB9cT.js:5251:11)
      at async handler
  (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/chunks/adapter-factory-HF3JB9cT.js:5273:16)
      at async fn
  (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@sveltejs+kit@2.49.1_@opentelemetry+api@1.9.0_@sveltejs+vite-plugin-svelte@6.2.1_rolldo_8a33769751fc7acf19d78df735624e9a/node_modules/@sveltejs/kit/src/exports/hooks/sequence.js:102:13)
      at null.<anonymous> (async
  file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:512768:14)


✘ [ERROR] # SERVER_ERROR:  Error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.

      at getCurrentRequestState
  (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:41:20)
      at async set
  (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:63:5)
      at async generateState
  (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-auth@1.4.5_@sveltejs+kit@2.49.1_@opentelemetry+api@1.9.0_@sveltejs+vite-plugin-s_2117d6321a543e35ae24707332b8d2bc/node_modules/better-auth/dist/utils-db7gNqd-.mjs:28:2)
      at null.<anonymous> (async
  file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:116425:26)
      at async internalHandler
  (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-call@1.1.4_zod@4.1.13/node_modules/better-call/src/endpoint.ts:503:20)
      at null.<anonymous> (async
  file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:141196:26)
      at async processRequest
  (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/chunks/adapter-factory-HF3JB9cT.js:5251:11)
      at async handler
  (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/chunks/adapter-factory-HF3JB9cT.js:5273:16)
      at async fn
  (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@sveltejs+kit@2.49.1_@opentelemetry+api@1.9.0_@sveltejs+vite-plugin-svelte@6.2.1_rolldo_8a33769751fc7acf19d78df735624e9a/node_modules/@sveltejs/kit/src/exports/hooks/sequence.js:102:13)
      at null.<anonymous> (async
  file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:512768:14)

[wrangler:info] POST /api/auth/sign-in/sso 500 Internal Server Error (91ms)
<!-- gh-comment-id:3627832726 --> @tnkuehne commented on GitHub (Dec 8, 2025): @dosu Ok, migrated it to use `await authClient.signIn.sso` on the client. But I get almost the same error: ```console ✘ [ERROR] 2025-12-08T16:07:31.136Z ERROR [Better Auth]: Error Error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback. at getCurrentRequestState (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:41:20) at async set (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:63:5) at async generateState (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-auth@1.4.5_@sveltejs+kit@2.49.1_@opentelemetry+api@1.9.0_@sveltejs+vite-plugin-s_2117d6321a543e35ae24707332b8d2bc/node_modules/better-auth/dist/utils-db7gNqd-.mjs:28:2) at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:116425:26) at async internalHandler (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-call@1.1.4_zod@4.1.13/node_modules/better-call/src/endpoint.ts:503:20) at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:141196:26) at async processRequest (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/chunks/adapter-factory-HF3JB9cT.js:5251:11) at async handler (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/chunks/adapter-factory-HF3JB9cT.js:5273:16) at async fn (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@sveltejs+kit@2.49.1_@opentelemetry+api@1.9.0_@sveltejs+vite-plugin-svelte@6.2.1_rolldo_8a33769751fc7acf19d78df735624e9a/node_modules/@sveltejs/kit/src/exports/hooks/sequence.js:102:13) at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:512768:14) ✘ [ERROR] # SERVER_ERROR: Error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback. at getCurrentRequestState (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:41:20) at async set (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@better-auth+core@1.4.5_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.18_better-call_c97e445e802b315319ad04ddb5da9384/node_modules/@better-auth/core/dist/context-DgQ9XGBl.mjs:63:5) at async generateState (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-auth@1.4.5_@sveltejs+kit@2.49.1_@opentelemetry+api@1.9.0_@sveltejs+vite-plugin-s_2117d6321a543e35ae24707332b8d2bc/node_modules/better-auth/dist/utils-db7gNqd-.mjs:28:2) at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:116425:26) at async internalHandler (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/better-call@1.1.4_zod@4.1.13/node_modules/better-call/src/endpoint.ts:503:20) at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:141196:26) at async processRequest (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/chunks/adapter-factory-HF3JB9cT.js:5251:11) at async handler (file:///home/timo/ZedProjects/enterprise/.svelte-kit/output/server/chunks/adapter-factory-HF3JB9cT.js:5273:16) at async fn (file:///home/timo/ZedProjects/enterprise/node_modules/.pnpm/@sveltejs+kit@2.49.1_@opentelemetry+api@1.9.0_@sveltejs+vite-plugin-svelte@6.2.1_rolldo_8a33769751fc7acf19d78df735624e9a/node_modules/@sveltejs/kit/src/exports/hooks/sequence.js:102:13) at null.<anonymous> (async file:///home/timo/ZedProjects/enterprise/.wrangler/tmp/dev-EJLAsd/_worker.js:512768:14) [wrangler:info] POST /api/auth/sign-in/sso 500 Internal Server Error (91ms) ```
Author
Owner

@dosubot[bot] commented on GitHub (Dec 8, 2025):

This error means the SSO initiation endpoint (/api/auth/sign-in/sso) is still being called in a way that doesn't have the required request context, even after moving to authClient.signIn.sso. In Better Auth v1.4+, all SSO/social sign-in flows must be started directly from the browser using the official client SDK, so the OAuth state cookie is set in the browser context—calling this endpoint from a custom API route, server action, or fetch handler will break request state and cause this error (details).

A few things to check:

  • Make sure your client code calls authClient.signIn.sso directly in the browser, not via a custom /api route or server endpoint.
  • Ensure your SvelteKit setup is using the official svelteKitHandler and sveltekitCookies plugin, and that all /api/auth/* routes are handled by the Better Auth handler, not intercepted by custom middleware or session logic (reference).
  • In Cloudflare Workers, do not export a singleton auth instance. Instead, create the auth instance inside each request handler to ensure request context is available (reference).
  • Double-check that your frontend is not proxying the SSO initiation through your own backend—this will break the required context.

If you’re already doing all of the above, please share how you’re invoking authClient.signIn.sso in your client code and how your SvelteKit endpoints are set up. This will help pinpoint where the request context is being lost.

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other

Chat with Dosu Open in Cursor Join Discord Share on X

<!-- gh-comment-id:3627872889 --> @dosubot[bot] commented on GitHub (Dec 8, 2025): <!-- Answer --> This error means the SSO initiation endpoint (`/api/auth/sign-in/sso`) is still being called in a way that doesn't have the required request context, even after moving to `authClient.signIn.sso`. In Better Auth v1.4+, all SSO/social sign-in flows must be started directly from the browser using the official client SDK, so the OAuth state cookie is set in the browser context—calling this endpoint from a custom API route, server action, or fetch handler will break request state and cause this error ([details](https://github.com/better-auth/better-auth/issues/5055)). A few things to check: - Make sure your client code calls `authClient.signIn.sso` directly in the browser, not via a custom `/api` route or server endpoint. - Ensure your SvelteKit setup is using the official `svelteKitHandler` and `sveltekitCookies` plugin, and that all `/api/auth/*` routes are handled by the Better Auth handler, not intercepted by custom middleware or session logic ([reference](https://github.com/better-auth/better-auth/issues/5413)). - In Cloudflare Workers, do not export a singleton `auth` instance. Instead, create the `auth` instance inside each request handler to ensure request context is available ([reference](https://github.com/better-auth/better-auth/issues/5413)). - Double-check that your frontend is not proxying the SSO initiation through your own backend—this will break the required context. If you’re already doing all of the above, please share how you’re invoking `authClient.signIn.sso` in your client code and how your SvelteKit endpoints are set up. This will help pinpoint where the request context is being lost. <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/0afc4c19-7cb9-4501-88b4-2fdccecbda8e?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/0afc4c19-7cb9-4501-88b4-2fdccecbda8e?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/0afc4c19-7cb9-4501-88b4-2fdccecbda8e?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/0afc4c19-7cb9-4501-88b4-2fdccecbda8e?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/0afc4c19-7cb9-4501-88b4-2fdccecbda8e?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/0afc4c19-7cb9-4501-88b4-2fdccecbda8e?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/0afc4c19-7cb9-4501-88b4-2fdccecbda8e?feedback_type=other)</sup> [![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Open in Cursor](https://dosu.dev/dosu-in-cursor.svg)](https://cursor.com/link/prompt?text=This%20error%20means%20the%20SSO%20initiation%20endpoint%20%28%60/api/auth/sign-in/sso%60%29%20is%20still%20being%20called%20in%20a%20way%20that%20doesn%27t%20have%20the%20required%20request%20context%2C%20even%20after%20moving%20to%20%60authClient.signIn.sso%60.%20In%20Better%20Auth%20v1.4%2B%2C%20all%20SSO/social%20sign-in%20flows%20must%20be%20started%20directly%20from%20the%20browser%20using%20the%20official%20client%20SDK%2C%20so%20the%20OAuth%20state%20cookie%20is%20set%20in%20the%20browser%20context%E2%80%94calling%20this%20endpoint%20from%20a%20custom%20API%20route%2C%20server%20action%2C%20or%20fetch%20handler%20will%20break%20request%20state%20and%20cause%20this%20error%20%28%5Bdetails%5D%28https%3A//github.com/better-auth/better-auth/issues/5055%29%29.%0A%0AA%20few%20things%20to%20check%3A%0A%0A-%20Make%20sure%20your%20client%20code%20calls%20%60authClient.signIn.sso%60%20directly%20in%20the%20browser%2C%20not%20via%20a%20custom%20%60/api%60%20route%20or%20server%20endpoint.%0A-%20Ensure%20your%20SvelteKit%20setup%20is%20using%20the%20official%20%60svelteKitHandler%60%20and%20%60sveltekitCookies%60%20plugin%2C%20and%20that%20all%20%60/api/auth/%2A%60%20routes%20are%20handled%20by%20the%20Better%20Auth%20handler%2C%20not%20intercepted%20by%20custom%20middleware%20or%20session%20logic%20%28%5Breference%5D%28https%3A//github.com/better-auth/better-auth/issues/5413%29%29.%0A-%20In%20Cloudflare%20Workers%2C%20do%20not%20export%20a%20singleton%20%60auth%60%20instance.%20Instead%2C%20create%20the%20%60auth%60%20instance%20inside%20each%20request%20handler%20to%20ensure%20request%20context%20is%20available%20%28%5Breference%5D%28https%3A//github.com/better-auth/better-auth/issues/5413%29%29.%0A-%20Double-check%20that%20your%20frontend%20is%20not%20proxying%20the%20SSO%20initiation%20through%20your%20own%20backend%E2%80%94this%20will%20break%20the%20required%20context.%0A%0AIf%20you%E2%80%99re%20already%20doing%20all%20of%20the%20above%2C%20please%20share%20how%20you%E2%80%99re%20invoking%20%60authClient.signIn.sso%60%20in%20your%20client%20code%20and%20how%20your%20SvelteKit%20endpoints%20are%20set%20up.%20This%20will%20help%20pinpoint%20where%20the%20request%20context%20is%20being%20lost.)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/6613)
Author
Owner

@tnkuehne commented on GitHub (Dec 8, 2025):

Hm, this is not at all helpful. Does any human have any advice on how to solve this?

<!-- gh-comment-id:3627990166 --> @tnkuehne commented on GitHub (Dec 8, 2025): Hm, this is not at all helpful. Does any human have any advice on how to solve this?
Author
Owner

@Bekacru commented on GitHub (Dec 9, 2025):

can you check if 1.4.6-beta.4 fixes this for you

<!-- gh-comment-id:3629662983 --> @Bekacru commented on GitHub (Dec 9, 2025): can you check if ` 1.4.6-beta.4` fixes this for you
Author
Owner

@tnkuehne commented on GitHub (Dec 9, 2025):

can you check if 1.4.6-beta.4 fixes this for you

Beta 4 was not available on npm, but I tried 1.4.6 and encountered a severe issue #6635, so I was unable to verify if the issue had been resolved.

Image
<!-- gh-comment-id:3631248845 --> @tnkuehne commented on GitHub (Dec 9, 2025): > can you check if ` 1.4.6-beta.4` fixes this for you Beta 4 was not available on npm, but I tried 1.4.6 and encountered a severe issue #6635, so I was unable to verify if the issue had been resolved. <img width="1003" height="1206" alt="Image" src="https://github.com/user-attachments/assets/ada2f4df-8b33-44c4-b5ea-7b56eccd3de2" />
Author
Owner

@kanishk1 commented on GitHub (Dec 9, 2025):

+1 seems the release for 1.4.6-beta.4 failed
https://github.com/better-auth/better-auth/actions/runs/20053818766/job/57514949040

<!-- gh-comment-id:3631458752 --> @kanishk1 commented on GitHub (Dec 9, 2025): +1 seems the release for 1.4.6-beta.4 failed https://github.com/better-auth/better-auth/actions/runs/20053818766/job/57514949040
Author
Owner

@apankov1 commented on GitHub (Dec 10, 2025):

+1

<!-- gh-comment-id:3637932124 --> @apankov1 commented on GitHub (Dec 10, 2025): +1
Author
Owner

@tnkuehne commented on GitHub (Dec 10, 2025):

can you check if 1.4.6-beta.4 fixes this for you

Tried it with 1.4.7-beta.2 and it still produces the same error.

<!-- gh-comment-id:3639276175 --> @tnkuehne commented on GitHub (Dec 10, 2025): > can you check if ` 1.4.6-beta.4` fixes this for you Tried it with `1.4.7-beta.2` and it still produces the same error.
Author
Owner

@praneybehl commented on GitHub (Dec 11, 2025):

While this issue is specifically about the runWithRequestState error in v1.4, I wanted to share a fix for a related Cloudflare Workers issue that others may encounter - the createRequire(import.meta.url) error.

If you're seeing:

TypeError: The argument 'path' must be a file URL object, file URL string, or absolute path string. Received 'undefined'
  at createRequire (node:module)

This happens because import.meta.url is undefined in Cloudflare Workers' bundled output. The fix uses Wrangler's module aliasing:

wrangler.toml:

compatibility_date = "2025-09-01"
compatibility_flags = ["nodejs_compat_v2"]

[alias]
"node:module" = "./src/polyfills/node-module.ts"

src/polyfills/node-module.ts:

export function createRequire(_filename: string | URL): NodeRequire {
  const req = function require(id: string): never {
    throw new Error(\`Cannot use require() in Cloudflare Workers.\`);
  };
  req.resolve = (id: string): never => { throw new Error(\`Cannot use require.resolve().\`); };
  req.resolve.paths = () => null;
  req.cache = {};
  req.extensions = {};
  req.main = undefined;
  return req as unknown as NodeRequire;
}
export function isBuiltin() { return false; }
export function findSourceMap() { return undefined; }
export function syncBuiltinESMExports() {}
export default { createRequire, isBuiltin, findSourceMap, syncBuiltinESMExports };

This provides a no-op polyfill that satisfies module resolution. Full details in #1375 and #175.

Tested with: Wrangler 4.53.0, BetterAuth 1.4.6, Hono 4.7.0

<!-- gh-comment-id:3640524717 --> @praneybehl commented on GitHub (Dec 11, 2025): ## Related: `createRequire` Error Fix for Cloudflare Workers While this issue is specifically about the `runWithRequestState` error in v1.4, I wanted to share a fix for a related Cloudflare Workers issue that others may encounter - the `createRequire(import.meta.url)` error. If you're seeing: ``` TypeError: The argument 'path' must be a file URL object, file URL string, or absolute path string. Received 'undefined' at createRequire (node:module) ``` This happens because `import.meta.url` is undefined in Cloudflare Workers' bundled output. The fix uses Wrangler's module aliasing: **`wrangler.toml`:** ```toml compatibility_date = "2025-09-01" compatibility_flags = ["nodejs_compat_v2"] [alias] "node:module" = "./src/polyfills/node-module.ts" ``` **`src/polyfills/node-module.ts`:** ```typescript export function createRequire(_filename: string | URL): NodeRequire { const req = function require(id: string): never { throw new Error(\`Cannot use require() in Cloudflare Workers.\`); }; req.resolve = (id: string): never => { throw new Error(\`Cannot use require.resolve().\`); }; req.resolve.paths = () => null; req.cache = {}; req.extensions = {}; req.main = undefined; return req as unknown as NodeRequire; } export function isBuiltin() { return false; } export function findSourceMap() { return undefined; } export function syncBuiltinESMExports() {} export default { createRequire, isBuiltin, findSourceMap, syncBuiltinESMExports }; ``` This provides a no-op polyfill that satisfies module resolution. Full details in #1375 and #175. **Tested with:** Wrangler 4.53.0, BetterAuth 1.4.6, Hono 4.7.0
Author
Owner

@Bekacru commented on GitHub (Dec 11, 2025):

We're on it. Should be fixed on the next release

<!-- gh-comment-id:3644254021 --> @Bekacru commented on GitHub (Dec 11, 2025): We're on it. Should be fixed on the next release
Author
Owner

@hcampbell98 commented on GitHub (Dec 14, 2025):

I'm still experiencing this issue on 1.4.7

<!-- gh-comment-id:3651775038 --> @hcampbell98 commented on GitHub (Dec 14, 2025): I'm still experiencing this issue on `1.4.7`
Author
Owner

@alexdonh commented on GitHub (Dec 24, 2025):

Encountering this issue now on 1.4.8 and 1.4.9 with the new oauthProvider plugin added. @Bekacru (@dvanmali just FYI)

<!-- gh-comment-id:3689157638 --> @alexdonh commented on GitHub (Dec 24, 2025): Encountering this issue now on 1.4.8 and 1.4.9 with the new oauthProvider plugin added. @Bekacru (@dvanmali just FYI)
Author
Owner

@ColaIan commented on GitHub (Dec 25, 2025):

Encountering this issue now on 1.4.9 sveltekit, works on dev but breaks when deployed via nixpacks bun, with sso() plugin defaultSSO oidcProvider. Not sure if it is related but it's also the runWithRequestState issue:

authClient.signIn.sso({ providerId: 'dev', callbackURL: '/dashboard' })
ERROR [Better Auth]: Error 36 | async function hasRequestState() {
37 | 	return (await ensureAsyncStorage$1()).getStore() !== void 0;
38 | }
39 | async function getCurrentRequestState() {
40 | 	const store = (await ensureAsyncStorage$1()).getStore();
41 | 	if (!store) throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");
^
error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.
at getCurrentRequestState (/app/node_modules/@better-auth/core/dist/context-DblZrIwO.mjs:41:24)
# SERVER_ERROR:  36 | async function hasRequestState() {
37 | 	return (await ensureAsyncStorage$1()).getStore() !== void 0;
38 | }
39 | async function getCurrentRequestState() {
40 | 	const store = (await ensureAsyncStorage$1()).getStore();
41 | 	if (!store) throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");
^
error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.
at getCurrentRequestState (/app/node_modules/@better-auth/core/dist/context-DblZrIwO.mjs:41:24)
<!-- gh-comment-id:3691004503 --> @ColaIan commented on GitHub (Dec 25, 2025): Encountering this issue now on 1.4.9 sveltekit, works on dev but breaks when deployed via nixpacks bun, with sso() plugin defaultSSO oidcProvider. Not sure if it is related but it's also the runWithRequestState issue: ``` authClient.signIn.sso({ providerId: 'dev', callbackURL: '/dashboard' }) ``` ``` ERROR [Better Auth]: Error 36 | async function hasRequestState() { 37 | return (await ensureAsyncStorage$1()).getStore() !== void 0; 38 | } 39 | async function getCurrentRequestState() { 40 | const store = (await ensureAsyncStorage$1()).getStore(); 41 | if (!store) throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback."); ^ error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback. at getCurrentRequestState (/app/node_modules/@better-auth/core/dist/context-DblZrIwO.mjs:41:24) # SERVER_ERROR: 36 | async function hasRequestState() { 37 | return (await ensureAsyncStorage$1()).getStore() !== void 0; 38 | } 39 | async function getCurrentRequestState() { 40 | const store = (await ensureAsyncStorage$1()).getStore(); 41 | if (!store) throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback."); ^ error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback. at getCurrentRequestState (/app/node_modules/@better-auth/core/dist/context-DblZrIwO.mjs:41:24) ```
Author
Owner

@aalwayslucky commented on GitHub (Dec 26, 2025):

Encountering this issue now on 1.4.8 and 1.4.9 with the new oauthProvider plugin added. @Bekacru (@dvanmali just FYI)

yeah tried to use new oauthProvider plugin also was happy already merged and now getting this on cloudfare same problem

SERVER_ERROR: Error: No request state found. Please make sure you are calling this function within a runWithRequestState callback.

<!-- gh-comment-id:3692059849 --> @aalwayslucky commented on GitHub (Dec 26, 2025): > Encountering this issue now on 1.4.8 and 1.4.9 with the new oauthProvider plugin added. [@Bekacru](https://github.com/Bekacru) ([@dvanmali](https://github.com/dvanmali) just FYI) yeah tried to use new oauthProvider plugin also was happy already merged and now getting this on cloudfare same problem SERVER_ERROR: Error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.
Author
Owner

@DarthGigi commented on GitHub (Dec 28, 2025):

I'd like to add that this issue is not limited to CF workers, happens with sveltekit's node adapter as well.

EDIT: I was wrong, this workaround is for a different issue where the request.headers are not being detected by better auth itself (but they do exist and are passed)

I found the following workaround:

Pass the request object from getRequestEvent() (remote functions) or from a +server.ts to a server API call. Client api calls work fine.

import { getRequestEvent, query } from "$app/server";

const { request } = getRequestEvent();
const response = await auth.api.signIn({
  headers: request.headers,
  body: {},
  request, // <-- add this
});
<!-- gh-comment-id:3694363794 --> @DarthGigi commented on GitHub (Dec 28, 2025): I'd like to add that this issue is not limited to CF workers, happens with sveltekit's node adapter as well. EDIT: I was wrong, this workaround is for a different issue where the `request.headers` are not being detected by better auth itself (but they do exist and are passed) I found the following workaround: Pass the request object from `getRequestEvent()` (remote functions) or from a `+server.ts` to a server API call. Client api calls work fine. ```ts import { getRequestEvent, query } from "$app/server"; const { request } = getRequestEvent(); const response = await auth.api.signIn({ headers: request.headers, body: {}, request, // <-- add this }); ```
Author
Owner

@barreeeiroo commented on GitHub (Dec 28, 2025):

For me, upgrading to the following beta versions worked:

bun add @better-auth/oauth-provider@1.4.10-beta.1 better-auth@1.4.10-beta.1

I did try the recommendation from @DarthGigi above, but with no luck. My issue only appeared when adding the new oauthProvider plugin: commenting it out also removed the bug.

<!-- gh-comment-id:3694961868 --> @barreeeiroo commented on GitHub (Dec 28, 2025): For me, upgrading to the following beta versions worked: ```bash bun add @better-auth/oauth-provider@1.4.10-beta.1 better-auth@1.4.10-beta.1 ``` I did try the recommendation from @DarthGigi above, but with no luck. My issue only appeared when adding the new `oauthProvider` plugin: commenting it out also removed the bug.
Author
Owner

@DarthGigi commented on GitHub (Jan 1, 2026):

Still an issue in the newly released 1.4.10 versions of better-auth and @better-auth/oauth-provider

<!-- gh-comment-id:3703946429 --> @DarthGigi commented on GitHub (Jan 1, 2026): Still an issue in the newly released `1.4.10` versions of `better-auth` and `@better-auth/oauth-provider`
Author
Owner

@himself65 commented on GitHub (Jan 2, 2026):

I'm fixing this

<!-- gh-comment-id:3704727308 --> @himself65 commented on GitHub (Jan 2, 2026): I'm fixing this
Author
Owner

@himself65 commented on GitHub (Jan 2, 2026):

While this issue is specifically about the runWithRequestState error in v1.4, I wanted to share a fix for a related Cloudflare Workers issue that others may encounter - the createRequire(import.meta.url) error.

If you're seeing:

TypeError: The argument 'path' must be a file URL object, file URL string, or absolute path string. Received 'undefined'
  at createRequire (node:module)

This happens because import.meta.url is undefined in Cloudflare Workers' bundled output. The fix uses Wrangler's module aliasing:

wrangler.toml:

compatibility_date = "2025-09-01"
compatibility_flags = ["nodejs_compat_v2"]

[alias]
"node:module" = "./src/polyfills/node-module.ts"
src/polyfills/node-module.ts:

export function createRequire(_filename: string | URL): NodeRequire {
const req = function require(id: string): never {
throw new Error(`Cannot use require() in Cloudflare Workers.`);
};
req.resolve = (id: string): never => { throw new Error(`Cannot use require.resolve().`); };
req.resolve.paths = () => null;
req.cache = {};
req.extensions = {};
req.main = undefined;
return req as unknown as NodeRequire;
}
export function isBuiltin() { return false; }
export function findSourceMap() { return undefined; }
export function syncBuiltinESMExports() {}
export default { createRequire, isBuiltin, findSourceMap, syncBuiltinESMExports };
This provides a no-op polyfill that satisfies module resolution. Full details in #1375 and #175.

Tested with: Wrangler 4.53.0, BetterAuth 1.4.6, Hono 4.7.0

This is another issue and we already fixed it

<!-- gh-comment-id:3704761271 --> @himself65 commented on GitHub (Jan 2, 2026): > ## Related: `createRequire` Error Fix for Cloudflare Workers > While this issue is specifically about the `runWithRequestState` error in v1.4, I wanted to share a fix for a related Cloudflare Workers issue that others may encounter - the `createRequire(import.meta.url)` error. > > If you're seeing: > > ``` > TypeError: The argument 'path' must be a file URL object, file URL string, or absolute path string. Received 'undefined' > at createRequire (node:module) > ``` > > This happens because `import.meta.url` is undefined in Cloudflare Workers' bundled output. The fix uses Wrangler's module aliasing: > > **`wrangler.toml`:** > > compatibility_date = "2025-09-01" > compatibility_flags = ["nodejs_compat_v2"] > > [alias] > "node:module" = "./src/polyfills/node-module.ts" > **`src/polyfills/node-module.ts`:** > > export function createRequire(_filename: string | URL): NodeRequire { > const req = function require(id: string): never { > throw new Error(\`Cannot use require() in Cloudflare Workers.\`); > }; > req.resolve = (id: string): never => { throw new Error(\`Cannot use require.resolve().\`); }; > req.resolve.paths = () => null; > req.cache = {}; > req.extensions = {}; > req.main = undefined; > return req as unknown as NodeRequire; > } > export function isBuiltin() { return false; } > export function findSourceMap() { return undefined; } > export function syncBuiltinESMExports() {} > export default { createRequire, isBuiltin, findSourceMap, syncBuiltinESMExports }; > This provides a no-op polyfill that satisfies module resolution. Full details in [#1375](https://github.com/better-auth/better-auth/issues/1375) and [#175](https://github.com/better-auth/better-auth/issues/175). > > **Tested with:** Wrangler 4.53.0, BetterAuth 1.4.6, Hono 4.7.0 This is another issue and we already fixed it
Author
Owner

@himself65 commented on GitHub (Jan 2, 2026):

For me, upgrading to the following beta versions worked:

bun add @better-auth/oauth-provider@1.4.10-beta.1 better-auth@1.4.10-beta.1
I did try the recommendation from @DarthGigi above, but with no luck. My issue only appeared when adding the new oauthProvider plugin: commenting it out also removed the bug.

Check the lock file and node modules

<!-- gh-comment-id:3704773033 --> @himself65 commented on GitHub (Jan 2, 2026): > For me, upgrading to the following beta versions worked: > > bun add @better-auth/oauth-provider@1.4.10-beta.1 better-auth@1.4.10-beta.1 > I did try the recommendation from [@DarthGigi](https://github.com/DarthGigi) above, but with no luck. My issue only appeared when adding the new `oauthProvider` plugin: commenting it out also removed the bug. Check the lock file and node modules
Author
Owner

@himself65 commented on GitHub (Jan 2, 2026):

I would doubt that the deeper issue is in the dist output could have a dual module hazard. because we in cloudflare you already enabled the async local storage

<!-- gh-comment-id:3704775762 --> @himself65 commented on GitHub (Jan 2, 2026): I would doubt that the deeper issue is in the dist output could have a dual module hazard. because we in cloudflare you already enabled the async local storage
Author
Owner

@zackliscio commented on GitHub (Jan 4, 2026):

@himself65 the fix in the PR I opened works to address the specific issue of oauthProvider breaking -- saw it was closed, so hoping someone will propose an alternative as this blocks adoption of the oauthProvider and 1.4 for us

<!-- gh-comment-id:3707470307 --> @zackliscio commented on GitHub (Jan 4, 2026): @himself65 the fix in the PR I opened works to address the specific issue of oauthProvider breaking -- saw it was closed, so hoping someone will propose an alternative as this blocks adoption of the oauthProvider and 1.4 for us
Author
Owner

@k-urtica commented on GitHub (Jan 12, 2026):

I've confirmed that this issue still persists with Better-Auth v1.4.11 and Nuxt v4.2.2 (in a Cloudflare Workers environment).

Unfortunately, due to this error, the library is completely unusable in a Workers environment at the moment.

A fundamental fix would be ideal, but if there are any temporary workarounds available, I would greatly appreciate it if you could share them.

<!-- gh-comment-id:3738857912 --> @k-urtica commented on GitHub (Jan 12, 2026): I've confirmed that this issue still persists with Better-Auth v1.4.11 and Nuxt v4.2.2 (in a Cloudflare Workers environment). Unfortunately, due to this error, the library is completely unusable in a Workers environment at the moment. A fundamental fix would be ideal, but if there are any temporary workarounds available, I would greatly appreciate it if you could share them.
Author
Owner

@himself65 commented on GitHub (Jan 12, 2026):

Sorry to say, but this is definitely a dual-module hazard in your repository setup. And I can be pretty sure to say that because I've set up Cloudflare Worker successfully without any errors.

Please check your repo lockfile to fix that

ref: https://gemini.google.com/share/6df423737984

<!-- gh-comment-id:3739567704 --> @himself65 commented on GitHub (Jan 12, 2026): Sorry to say, but this is definitely a dual-module hazard in your repository setup. And I can be pretty sure to say that because I've set up Cloudflare Worker successfully without any errors. Please check your repo lockfile to fix that ref: https://gemini.google.com/share/6df423737984
Author
Owner

@DarthGigi commented on GitHub (Jan 12, 2026):

@himself65 This is not limited to Cloudflare Workers, it also happens when using the new oauthProvider plugin introduced in 1.4 on NodeJS backends:

Could this issue be re-opened and the title be changed?

<!-- gh-comment-id:3739603262 --> @DarthGigi commented on GitHub (Jan 12, 2026): @himself65 This is not limited to Cloudflare Workers, it also happens when using the new oauthProvider plugin introduced in 1.4 on NodeJS backends: - https://github.com/better-auth/better-auth/issues/6613#issuecomment-3707470307 - https://github.com/better-auth/better-auth/issues/6613#issuecomment-3689157638 - https://github.com/better-auth/better-auth/issues/6613#issuecomment-3691004503 - https://github.com/better-auth/better-auth/issues/6613#issuecomment-3694363794 Could this issue be re-opened and the title be changed?
Author
Owner

@himself65 commented on GitHub (Jan 12, 2026):

@himself65 This is not limited to Cloudflare Workers, it also happens when using the new oauthProvider plugin introduced in 1.4 on NodeJS backends:

Could this issue be re-opened and the title be changed?

Yes, it cannot be limited to Cloudflare Workers, so please provide a reproducible repository, and I will fix it.

<!-- gh-comment-id:3739688064 --> @himself65 commented on GitHub (Jan 12, 2026): > [@himself65](https://github.com/himself65) This is not limited to Cloudflare Workers, it also happens when using the new oauthProvider plugin introduced in 1.4 on NodeJS backends: > > * [Upgrade from 1.3 to 1.4: Error runWithRequestState on cloudflare workers #6613 (comment)](https://github.com/better-auth/better-auth/issues/6613#issuecomment-3707470307) > * [Upgrade from 1.3 to 1.4: Error runWithRequestState on cloudflare workers #6613 (comment)](https://github.com/better-auth/better-auth/issues/6613#issuecomment-3689157638) > * [Upgrade from 1.3 to 1.4: Error runWithRequestState on cloudflare workers #6613 (comment)](https://github.com/better-auth/better-auth/issues/6613#issuecomment-3691004503) > * [Upgrade from 1.3 to 1.4: Error runWithRequestState on cloudflare workers #6613 (comment)](https://github.com/better-auth/better-auth/issues/6613#issuecomment-3694363794) > > Could this issue be re-opened and the title be changed? Yes, it cannot be limited to Cloudflare Workers, so please provide a reproducible repository, and I will fix it.
Author
Owner

@himself65 commented on GitHub (Jan 12, 2026):

We will update the document about how to investigate the dual module hazard bug.

<!-- gh-comment-id:3739783138 --> @himself65 commented on GitHub (Jan 12, 2026): We will update the document about how to investigate the dual module hazard bug.
Author
Owner

@himself65 commented on GitHub (Jan 12, 2026):

Right now you can run pnpm why @better-auth/core, pnpm why better-auth to see what is going on

<!-- gh-comment-id:3739817010 --> @himself65 commented on GitHub (Jan 12, 2026): Right now you can run `pnpm why @better-auth/core`, `pnpm why better-auth` to see what is going on
Author
Owner

@himself65 commented on GitHub (Jan 12, 2026):

BTW, we have added a warning if it detects the dual module, https://github.com/better-auth/better-auth/commit/1baaa9c81

Please try 1.4.11 to see if you can see the warning

<!-- gh-comment-id:3739952738 --> @himself65 commented on GitHub (Jan 12, 2026): BTW, we have added a warning if it detects the dual module, https://github.com/better-auth/better-auth/commit/1baaa9c81 Please try 1.4.11 to see if you can see the warning
Author
Owner

@DarthGigi commented on GitHub (Jan 12, 2026):

Yes, it cannot be limited to Cloudflare Workers, so please provide a reproducible repository, and I will fix it.

@himself65 I've made a MVCE of this issue as requested: https://github.com/DarthGigi/better-auth-oauthplugin-mvce

<!-- gh-comment-id:3740253311 --> @DarthGigi commented on GitHub (Jan 12, 2026): > Yes, it cannot be limited to Cloudflare Workers, so please provide a reproducible repository, and I will fix it. @himself65 I've made a MVCE of this issue as requested: https://github.com/DarthGigi/better-auth-oauthplugin-mvce
Author
Owner

@himself65 commented on GitHub (Jan 12, 2026):

I can reproduce this and have listed the detailed solution

There could be two issues here, but not on the better-auth side.

  1. Yarn v1 module resolution issue (maybe other package managers could have a similar issue)
  2. Next.js (turbopack), or Vite bundler module resolution issue

For 1

Please manually install better-call, and add the resolutions section. This will force making better-call to the top level.

 "dependencies": {
    // ...
    "better-call": "^1.1.8",
    // ...
  },
  "resolutions": {
    "better-call": "^1.1.8"
  },

/cc @tjx666 (you are using pnpm, but I think the same, pnpm v9 could have a similar issue, I tried on yarn v3 and pnpm 12, and it works well)

For 2

This is tricky, you can check https://github.com/yjs/yjs/issues/438

Basically, please use resolve.alias for webpack, resolve.dedupe for Vite, or add better-auth in serverExternalPackages for Next.js

There's not only one solution, but what we are doing here is trying to make Bundler resolve the module to the same instance


Please redirect to the issue https://github.com/better-auth/better-auth/issues/7023#issuecomment-3740635680. These two issues are actually the same. I will lock this issue as a duplicate

<!-- gh-comment-id:3740647926 --> @himself65 commented on GitHub (Jan 12, 2026): I can reproduce this and have listed the detailed solution There could be two issues here, but not on the better-auth side. 1. Yarn v1 module resolution issue (maybe other package managers could have a similar issue) 2. Next.js (turbopack), or Vite bundler module resolution issue For 1 Please manually install `better-call`, and add the `resolutions` section. This will force making `better-call` to the top level. ```jsonc "dependencies": { // ... "better-call": "^1.1.8", // ... }, "resolutions": { "better-call": "^1.1.8" }, ``` /cc @tjx666 (you are using pnpm, but I think the same, pnpm v9 could have a similar issue, I tried on yarn v3 and pnpm 12, and it works well) For 2 This is tricky, you can check https://github.com/yjs/yjs/issues/438 Basically, please use `resolve.alias` for webpack, `resolve.dedupe` for Vite, or add `better-auth` in `serverExternalPackages` for Next.js There's not only one solution, but what we are doing here is trying to make Bundler resolve the module to the same instance --- Please redirect to the issue https://github.com/better-auth/better-auth/issues/7023#issuecomment-3740635680. These two issues are actually the same. I will lock this issue as a duplicate
Author
Owner

@himself65 commented on GitHub (Jan 13, 2026):

https://www.better-auth.com/docs/reference/faq#dual-module-hazard-issue

<!-- gh-comment-id:3741086045 --> @himself65 commented on GitHub (Jan 13, 2026): https://www.better-auth.com/docs/reference/faq#dual-module-hazard-issue
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#19203