Upload project to cloudflare #1890

Closed
opened 2026-03-13 09:11:00 -05:00 by GiteaMirror · 4 comments
Owner

Originally created by @Christonn93 on GitHub (Sep 9, 2025).

Originally assigned to: @himself65 on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

Upload to cloudflare, uploaded sucessfull, but got this issue when trying to enter the page.

index-CiIw5mxx.js:146 Uncaught SyntaxError: 'super' keyword unexpected here

Current vs. Expected behavior

index-CiIw5mxx.js:146 Uncaught SyntaxError: 'super' keyword unexpected here - Did not expect this, expected it to work.

What version of Better Auth are you using?

0.4.0

System info

$ npx @better-auth/cli info --json
Need to install the following packages:
@better-auth/cli@1.3.9
Ok to proceed? (y) y

{
  "system": {
    "platform": "win32",
    "arch": "x64",
    "version": "Windows 11 Home",
    "release": "10.0.26100",
    "cpuCount": 8,
    "cpuModel": "AMD Ryzen 5 7520U with Radeon Graphics         ",
    "totalMemory": "15.24 GB",
    "freeMemory": "1.70 GB"
  },
  "node": {
    "version": "v22.15.0",
    "env": "development"
  },
  "packageManager": {
    "name": "npm",
    "version": "11.4.2"
  },
  "frameworks": null,
  "databases": [
    {
      "name": "@libsql/client",
      "version": "^0.15.14"
    },
    {
      "name": "drizzle",
      "version": "^0.44.5"
    }
  ],
  "betterAuth": {
    "version": "0.4.0",
    "config": null
  }
}
npm notice
npm notice New minor version of npm available! 11.4.2 -> 11.6.0
npm notice Changelog: https://github.com/npm/cli/releases/tag/v11.6.0
npm notice To update run: npm install -g npm@11.6.0
npm notice

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

Backend, Client, Types, Documentation

Auth config (if applicable)

async function getUserOrganizations(userId: string) {
  try {
    console.log("Fetching organizations for user:", userId);

    const db = getDb();
    if (!db) {
      throw new Error("Database not initialized");
    }

    const result = await db
      .select({
        id: schema.organization.id,
        name: schema.organization.name,
        slug: schema.organization.slug,
        logo: schema.organization.logo,
        createdAt: schema.organization.createdAt,
        metadata: schema.organization.metadata,
        role: schema.member.role,
        membershipId: schema.member.id,
      })
      .from(schema.organization)
      .innerJoin(schema.member, eq(schema.organization.id, schema.member.organizationId))
      .where(eq(schema.member.userId, userId));

    console.log("Found organizations:", result);
    return result;
  } catch (error) {
    console.error("Error fetching user organizations:", error);
    return [];
  }
}

let authInstance: any = null;

function createAuth() {
  if (authInstance) {
    return authInstance;
  }

  const db = getDb();
  if (!db) {
    throw new Error("Database not initialized - make sure database middleware runs first");
  }

  authInstance = betterAuth({
    database: drizzleAdapter(db, {
      provider: "sqlite",
      schema: {
        user: schema.user,
        session: schema.session,
        account: schema.account,
        verification: schema.verification,
        organization: schema.organization,
        member: schema.member,
        invitation: schema.invitation,
      },
    }),

    emailAndPassword: {
      enabled: true,
      requireEmailVerification: false,
    },

    secret: process.env.BETTER_AUTH_SECRET || "dev-secret",
    baseURL: process.env.BETTER_AUTH_URL_TUNNEL || process.env.BETTER_AUTH_URL || "http://localhost:3000",
    trustedOrigins: [
      process.env.BETTER_AUTH_CLIENT_URL_TUNNEL,
      process.env.BETTER_AUTH_CLIENT_URL,
      "http://localhost:5173",
      "https://wwggxc3g-5173.uks1.devtunnels.ms"
    ].filter((url): url is string => Boolean(url)),

    plugins: [
      admin(),
      organization({
        allowUserToCreateOrganization: true,
        requireInvitation: false,
      }),
      // Add custom session plugin to include organization data
      customSession(async ({ user, session }) => {
        console.log("Custom session callback triggered for user:", user.id);

        try {
          // Add organization data to session
          const organizations = await getUserOrganizations(user.id);
          const activeOrganization = organizations[0] || null;
          const userRole = activeOrganization?.role || "user";

          console.log(`Custom session result:`, {
            userId: user.id,
            organizationsCount: organizations.length,
            activeOrg: activeOrganization?.name,
            role: userRole,
          });

          return {
            user,
            session,
            organizations,
            activeOrganization,
            userRole,
          };
        } catch (error) {
          console.error("Error in custom session callback:", error);
          return {
            user,
            session,
            organizations: [],
            activeOrganization: null,
            userRole: "user",
          };
        }
      }),
    ],

    session: {
      enabled: true,
      cookieCache: {
        enabled: true,
      },
    },
  });

  return authInstance;
}

export const auth = new Proxy({} as any, {
  get(target, prop) {
    const authObj = createAuth();
    return authObj[prop];
  }
});

// // Export types separately without triggering the complex type serialization
// export type AuthHandler = (request: Request) => Promise<Response>;
// export type AuthAPI = typeof auth.api;

// // If you need to use the auth type elsewhere, use this pattern:
// type ExtractAuthType<T> = T extends ReturnType<typeof betterAuth> ? T : never;
// export type Auth = ExtractAuthType<typeof auth>;

export default auth;

Additional context

This is authClient

import { createAuthClient } from "better-auth/client";
import { organizationClient, customSessionClient, adminClient } from "better-auth/client/plugins";
import { API_BASE_URL } from "./config";

export const authClient = createAuthClient({
baseURL: API_BASE_URL + "/auth",
fetchOptions: {
credentials: "include",
},
plugins: [organizationClient(), customSessionClient(), adminClient()],
});

Originally created by @Christonn93 on GitHub (Sep 9, 2025). Originally assigned to: @himself65 on GitHub. ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce Upload to cloudflare, uploaded sucessfull, but got this issue when trying to enter the page. index-CiIw5mxx.js:146 Uncaught SyntaxError: 'super' keyword unexpected here ### Current vs. Expected behavior index-CiIw5mxx.js:146 Uncaught SyntaxError: 'super' keyword unexpected here - Did not expect this, expected it to work. ### What version of Better Auth are you using? 0.4.0 ### System info ```bash $ npx @better-auth/cli info --json Need to install the following packages: @better-auth/cli@1.3.9 Ok to proceed? (y) y { "system": { "platform": "win32", "arch": "x64", "version": "Windows 11 Home", "release": "10.0.26100", "cpuCount": 8, "cpuModel": "AMD Ryzen 5 7520U with Radeon Graphics ", "totalMemory": "15.24 GB", "freeMemory": "1.70 GB" }, "node": { "version": "v22.15.0", "env": "development" }, "packageManager": { "name": "npm", "version": "11.4.2" }, "frameworks": null, "databases": [ { "name": "@libsql/client", "version": "^0.15.14" }, { "name": "drizzle", "version": "^0.44.5" } ], "betterAuth": { "version": "0.4.0", "config": null } } npm notice npm notice New minor version of npm available! 11.4.2 -> 11.6.0 npm notice Changelog: https://github.com/npm/cli/releases/tag/v11.6.0 npm notice To update run: npm install -g npm@11.6.0 npm notice ``` ### Which area(s) are affected? (Select all that apply) Backend, Client, Types, Documentation ### Auth config (if applicable) ```typescript async function getUserOrganizations(userId: string) { try { console.log("Fetching organizations for user:", userId); const db = getDb(); if (!db) { throw new Error("Database not initialized"); } const result = await db .select({ id: schema.organization.id, name: schema.organization.name, slug: schema.organization.slug, logo: schema.organization.logo, createdAt: schema.organization.createdAt, metadata: schema.organization.metadata, role: schema.member.role, membershipId: schema.member.id, }) .from(schema.organization) .innerJoin(schema.member, eq(schema.organization.id, schema.member.organizationId)) .where(eq(schema.member.userId, userId)); console.log("Found organizations:", result); return result; } catch (error) { console.error("Error fetching user organizations:", error); return []; } } let authInstance: any = null; function createAuth() { if (authInstance) { return authInstance; } const db = getDb(); if (!db) { throw new Error("Database not initialized - make sure database middleware runs first"); } authInstance = betterAuth({ database: drizzleAdapter(db, { provider: "sqlite", schema: { user: schema.user, session: schema.session, account: schema.account, verification: schema.verification, organization: schema.organization, member: schema.member, invitation: schema.invitation, }, }), emailAndPassword: { enabled: true, requireEmailVerification: false, }, secret: process.env.BETTER_AUTH_SECRET || "dev-secret", baseURL: process.env.BETTER_AUTH_URL_TUNNEL || process.env.BETTER_AUTH_URL || "http://localhost:3000", trustedOrigins: [ process.env.BETTER_AUTH_CLIENT_URL_TUNNEL, process.env.BETTER_AUTH_CLIENT_URL, "http://localhost:5173", "https://wwggxc3g-5173.uks1.devtunnels.ms" ].filter((url): url is string => Boolean(url)), plugins: [ admin(), organization({ allowUserToCreateOrganization: true, requireInvitation: false, }), // Add custom session plugin to include organization data customSession(async ({ user, session }) => { console.log("Custom session callback triggered for user:", user.id); try { // Add organization data to session const organizations = await getUserOrganizations(user.id); const activeOrganization = organizations[0] || null; const userRole = activeOrganization?.role || "user"; console.log(`Custom session result:`, { userId: user.id, organizationsCount: organizations.length, activeOrg: activeOrganization?.name, role: userRole, }); return { user, session, organizations, activeOrganization, userRole, }; } catch (error) { console.error("Error in custom session callback:", error); return { user, session, organizations: [], activeOrganization: null, userRole: "user", }; } }), ], session: { enabled: true, cookieCache: { enabled: true, }, }, }); return authInstance; } export const auth = new Proxy({} as any, { get(target, prop) { const authObj = createAuth(); return authObj[prop]; } }); // // Export types separately without triggering the complex type serialization // export type AuthHandler = (request: Request) => Promise<Response>; // export type AuthAPI = typeof auth.api; // // If you need to use the auth type elsewhere, use this pattern: // type ExtractAuthType<T> = T extends ReturnType<typeof betterAuth> ? T : never; // export type Auth = ExtractAuthType<typeof auth>; export default auth; ``` ### Additional context This is authClient import { createAuthClient } from "better-auth/client"; import { organizationClient, customSessionClient, adminClient } from "better-auth/client/plugins"; import { API_BASE_URL } from "./config"; export const authClient = createAuthClient({ baseURL: API_BASE_URL + "/auth", fetchOptions: { credentials: "include", }, plugins: [organizationClient(), customSessionClient(), adminClient()], });
GiteaMirror added the javascript label 2026-03-13 09:11:00 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Sep 9, 2025):

Hi @Christonn93! I'm Dosu and I’m helping the better-auth team.

The error 'Uncaught SyntaxError: 'super' keyword unexpected here' usually means some ES6+ code (like classes using super) wasn't transpiled for the Cloudflare runtime. This is a known issue when using Better Auth with modern build tools and serverless platforms.

To fix this, make sure your build tool (like Vite) is not pre-bundling or optimizing the better-auth package. If you're using Vite, add this to your config:

vite: {
  optimizeDeps: {
    exclude: ['better-auth']
  }
}

This prevents Vite from transforming better-auth in a way that breaks class inheritance, which causes the super error on Cloudflare.
See details here.

If you need a quick workaround, you can temporarily downgrade to better-auth@1.3.7, which avoids this issue until a permanent fix lands in a future release.

There are no explicit Cloudflare build instructions in the Better Auth codebase, so you must ensure your build outputs code compatible with your Cloudflare environment. If you use another bundler or framework, check its docs for how to exclude dependencies from optimization or transpile all dependencies to ES5.

Let me know if you need help with a specific build setup.

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

@dosubot[bot] commented on GitHub (Sep 9, 2025): <!-- Greeting --> Hi @Christonn93! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> The error `'Uncaught SyntaxError: 'super' keyword unexpected here'` usually means some ES6+ code (like classes using `super`) wasn't transpiled for the Cloudflare runtime. This is a known issue when using Better Auth with modern build tools and serverless platforms. To fix this, make sure your build tool (like Vite) is not pre-bundling or optimizing the `better-auth` package. If you're using Vite, add this to your config: ```js vite: { optimizeDeps: { exclude: ['better-auth'] } } ``` This prevents Vite from transforming `better-auth` in a way that breaks class inheritance, which causes the `super` error on Cloudflare. See details [here](https://github.com/better-auth/better-auth/issues/4457). If you need a quick workaround, you can temporarily downgrade to `better-auth@1.3.7`, which avoids this issue until a permanent fix lands in a future release. There are no explicit Cloudflare build instructions in the Better Auth codebase, so you must ensure your build outputs code compatible with your Cloudflare environment. If you use another bundler or framework, check its docs for how to exclude dependencies from optimization or transpile all dependencies to ES5. Let me know if you need help with a specific build setup. <!-- 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/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&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/4541)
Author
Owner

@Christonn93 commented on GitHub (Sep 9, 2025):

Hi @Christonn93! I'm Dosu and I’m helping the better-auth team.

The error 'Uncaught SyntaxError: 'super' keyword unexpected here' usually means some ES6+ code (like classes using super) wasn't transpiled for the Cloudflare runtime. This is a known issue when using Better Auth with modern build tools and serverless platforms.

To fix this, make sure your build tool (like Vite) is not pre-bundling or optimizing the better-auth package. If you're using Vite, add this to your config:

vite: {
optimizeDeps: {
exclude: ['better-auth']
}
}
This prevents Vite from transforming better-auth in a way that breaks class inheritance, which causes the super error on Cloudflare. See details here.

If you need a quick workaround, you can temporarily downgrade to better-auth@1.3.7, which avoids this issue until a permanent fix lands in a future release.

There are no explicit Cloudflare build instructions in the Better Auth codebase, so you must ensure your build outputs code compatible with your Cloudflare environment. If you use another bundler or framework, check its docs for how to exclude dependencies from optimization or transpile all dependencies to ES5.

Let me know if you need help with a specific build setup.

To reply, just mention @dosu.

How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X


I already have this in my vite config.

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
import path from "node:path";
import { tanstackRouter } from "@tanstack/router-plugin/vite";
import { devtools } from "@tanstack/devtools-vite";

export default defineConfig({
  plugins: [
    devtools(),
    tanstackRouter({
      target: "react",
      autoCodeSplitting: true,
    }),
    react(),
    tailwindcss(),
  ],
  server: {
    proxy: {
      "/api": {
        target: process.env.VITE_API_BASE_URL || process.env.VITEAPI_BASE_URL_TUNNEL || "http://localhost:3000",
        changeOrigin: true,
        secure: false,
      },
    },
  },
  optimizeDeps: {
    exclude: ["better-auth"],
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
});
@Christonn93 commented on GitHub (Sep 9, 2025): > Hi [@Christonn93](https://github.com/Christonn93)! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. > > The error `'Uncaught SyntaxError: 'super' keyword unexpected here'` usually means some ES6+ code (like classes using `super`) wasn't transpiled for the Cloudflare runtime. This is a known issue when using Better Auth with modern build tools and serverless platforms. > > To fix this, make sure your build tool (like Vite) is not pre-bundling or optimizing the `better-auth` package. If you're using Vite, add this to your config: > > vite: { > optimizeDeps: { > exclude: ['better-auth'] > } > } > This prevents Vite from transforming `better-auth` in a way that breaks class inheritance, which causes the `super` error on Cloudflare. See details [here](https://github.com/better-auth/better-auth/issues/4457). > > If you need a quick workaround, you can temporarily downgrade to `better-auth@1.3.7`, which avoids this issue until a permanent fix lands in a future release. > > There are no explicit Cloudflare build instructions in the Better Auth codebase, so you must ensure your build outputs code compatible with your Cloudflare environment. If you use another bundler or framework, check its docs for how to exclude dependencies from optimization or transpile all dependencies to ES5. > > Let me know if you need help with a specific build setup. > > _To reply, just mention [@dosu](https://go.dosu.dev/dosubot)._ > > How did I do? [Good](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/fa6a908e-aa3f-468e-8a66-1f4eae01eece?feedback_type=other)  [![Chat with Dosu](https://camo.githubusercontent.com/d9ffebb979729c9ef0fc4e3090dbae5b17cabbfec8afe378ada6b81913d6ad8a/68747470733a2f2f646f73752e6465762f646f73752d636861742d62616467652e737667)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github) [![Join Discord](https://camo.githubusercontent.com/d562c2df5e4567ea41d37f1d91a4da0839d8341037045b103b2da268998de17f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6a6f696e2d3538363546323f6c6f676f3d646973636f7264266c6f676f436f6c6f723d7768697465266c6162656c3d)](https://go.dosu.dev/discord-bot) [![Share on X](https://camo.githubusercontent.com/4649f705e2396d6f328dbc8e800a0509c9c17b3b20253b36706c393df124b93d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f582d73686172652d626c61636b)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/4541) --- I already have this in my vite config. ``` import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import tailwindcss from "@tailwindcss/vite"; import path from "node:path"; import { tanstackRouter } from "@tanstack/router-plugin/vite"; import { devtools } from "@tanstack/devtools-vite"; export default defineConfig({ plugins: [ devtools(), tanstackRouter({ target: "react", autoCodeSplitting: true, }), react(), tailwindcss(), ], server: { proxy: { "/api": { target: process.env.VITE_API_BASE_URL || process.env.VITEAPI_BASE_URL_TUNNEL || "http://localhost:3000", changeOrigin: true, secure: false, }, }, }, optimizeDeps: { exclude: ["better-auth"], }, resolve: { alias: { "@": path.resolve(__dirname, "./src"), }, }, }); ```
Author
Owner

@himself65 commented on GitHub (Sep 11, 2025):

Have you tried with the latest better-auth? I think it should be fixed in 1.3.9

@himself65 commented on GitHub (Sep 11, 2025): Have you tried with the latest better-auth? I think it should be fixed in 1.3.9
Author
Owner

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

Hi, @Christonn93. I'm Dosu, and I'm helping the better-auth team manage their backlog and am marking this issue as stale.

Issue Summary:

  • You encountered a "Uncaught SyntaxError: 'super' keyword unexpected here" error when deploying better-auth v0.4.0 on Cloudflare.
  • You had already excluded better-auth from Vite's optimization as recommended.
  • Another user suggested upgrading to better-auth version 1.3.9, which may resolve the issue.
  • The issue appears to have been resolved by using version 1.3.9.

Next Steps:

  • Please confirm if this issue is still relevant with the latest version of better-auth.
  • If it is, feel free to comment here to keep the discussion open; otherwise, I will close this issue automatically in 7 days.

Thanks for your understanding and contribution!

@dosubot[bot] commented on GitHub (Dec 11, 2025): Hi, @Christonn93. I'm [Dosu](https://dosu.dev), and I'm helping the better-auth team manage their backlog and am marking this issue as stale. **Issue Summary:** - You encountered a "Uncaught SyntaxError: 'super' keyword unexpected here" error when deploying better-auth v0.4.0 on Cloudflare. - You had already excluded better-auth from Vite's optimization as recommended. - Another user suggested upgrading to better-auth version 1.3.9, which may resolve the issue. - The issue appears to have been resolved by using version 1.3.9. **Next Steps:** - Please confirm if this issue is still relevant with the latest version of better-auth. - If it is, feel free to comment here to keep the discussion open; otherwise, I will close this issue automatically in 7 days. Thanks for your understanding and contribution!
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#1890