better auth fails to build with bun runtime in nextjs 16 #2542

Closed
opened 2026-03-13 10:01:41 -05:00 by GiteaMirror · 5 comments
Owner

Originally created by @AmariUwU on GitHub (Dec 15, 2025).

Originally assigned to: @himself65 on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Install better auth in a nextjs 16 project
  2. Set up better auth configuration
  3. Use better auth in server components (e.g: auth pages)
  4. Build with bun runtime:
   bun --bun next build
  1. Build fails with chunk resolution error

Current vs. Expected behavior

Current behavior:

[MDX] generated files in 15.07799ms
   ▲ Next.js 16.0.10 (Turbopack, Cache Components)
   - Environments: .env

   Creating an optimized production build ...
 ✓ Compiled successfully in 45s
 ✓ Finished TypeScript in 35.1s    
   Collecting page data using 2 workers  ...Error: Failed to load chunk server/chunks/ssr/bb1a9_better-auth_dist_adapters_kysely-adapter_dialect_mjs_7c6a251c._.js from runtime for chunk server/app/(main)/organization/new/page.js
    at loadRuntimeChunkPath (.next/server/chunks/ssr/[turbopack]_runtime.js:636:19)
    at loadRuntimeChunk (.next/server/chunks/ssr/[turbopack]_runtime.js:605:9)
    at c (.next/server/chunks/ssr/[turbopack]_runtime.js:766:25)
    at <anonymous> (.next/server/app/(main)/organization/new/page.js:21:3)
    at anonymous (null)
    at processTicksAndRejections (null) {
  [cause]: ResolveMessage {}
}

> Build error occurred
Error: Failed to collect page data for /organization/new
    at processTicksAndRejections (null) {
  type: 'Error'
}
error: "next" exited with code 1
error: script "build" exited with code 1

Expected behavior:
better auth should build successfully with bun runtime, similar to how it works with node.

What version of Better Auth are you using?

1.4.6

System info

{
  "system": {
    "platform": "linux",
    "arch": "x64",
    "version": "#1 SMP PREEMPT_DYNAMIC Thu Jun  5 18:30:46 UTC 2025",
    "release": "6.6.87.2-microsoft-standard-WSL2",
    "cpuCount": 3,
    "cpuModel": "Intel(R) Core(TM) i5-10210U CPU @ 1.60GHz",
    "totalMemory": "7.64 GB",
    "freeMemory": "4.39 GB"
  },
  "node": {
    "version": "v24.2.0",
    "env": "production"
  },
  "packageManager": {
    "name": "bun",
    "version": "1.3.5"
  },
  "frameworks": [
    {
      "name": "next",
      "version": "16.0.10"
    },
    {
      "name": "react",
      "version": "^19.2.3"
    }
  ],
  "databases": [
    {
      "name": "pg",
      "version": "^8.16.3"
    },
    {
      "name": "drizzle",
      "version": "^0.45.1"
    }
  ],
  "betterAuth": {
    "version": "^1.4.6",
    "config": {
      "baseURL": "http://localhost:4321",
      "basePath": "/api/auth",
      "experimental": {
        "joins": true
      },
      "appName": "Ecom",
      "telemetry": {
        "enabled": false
      },
      "disabledPaths": [
        ""
      ],
      "session": {
        "freshAge": 300,
        "expiresIn": 604800,
        "cookieCache": {
          "enabled": true,
          "maxAge": 900
        },
        "storeSessionInDatabase": true
      },
      "rateLimit": {
        "enabled": true
      },
      "advanced": {
        "ipAddress": {
          "ipAddressHeaders": [
            "cf-connecting-ip",
            "x-forwarded-for"
          ]
        },
        "crossSubDomainCookies": {
          "enabled": true,
          "domain": "localhost"
        },
        "cookiePrefix": "domain",
        "useSecureCookies": true
      },
      "trustedOrigins": [
        "http://localhost:4321",
        "http://localhost:3000"
      ],
      "user": {
        "changeEmail": {
          "enabled": true,
          "updateEmailWithoutVerification": false
        }
      },
      "emailAndPassword": {
        "enabled": true,
        "autoSignIn": true,
        "revokeSessionsOnPasswordReset": true,
        "maxPasswordLength": 64,
        "minPasswordLength": 8,
        "requireEmailVerification": true,
        "resetPasswordTokenExpiresIn": 1800,
        "password": {}
      },
      "emailVerification": {
        "autoSignInAfterVerification": true,
        "sendOnSignIn": true,
        "sendOnSignUp": true,
        "expiresIn": 1800
      },
      "account": {
        "accountLinking": {
          "enabled": true
        }
      },
      "socialProviders": {
        "google": {
          "clientId": "[REDACTED]",
          "clientSecret": "[REDACTED]"
        },
        "microsoft": {
          "clientId": "[REDACTED]",
          "clientSecret": "[REDACTED]"
        }
      },
      "secondaryStorage": {},
      "databaseHooks": {
        "session": {
          "create": {}
        }
      },
      "plugins": [
        {
          "name": "last-login-method",
          "config": {
            "id": "last-login-method",
            "hooks": {
              "after": [
                {}
              ]
            },
            "schema": {
              "user": {
                "fields": {
                  "lastLoginMethod": {
                    "type": "string",
                    "input": false,
                    "required": false,
                    "fieldName": "lastLoginMethod"
                  }
                }
              }
            }
          }
        },
        {
          "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",
              "YOU_CANNOT_IMPERSONATE_ADMINS": "You cannot impersonate admins",
              "INVALID_ROLE_TYPE": "Invalid role type"
            },
            "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
                  }
                }
              }
            },
            "options": {}
          }
        },
        {
          "name": "two-factor",
          "config": {
            "id": "two-factor",
            "endpoints": {},
            "options": {
              "otpOptions": {
                "period": 3,
                "digits": 6,
                "allowedAttempts": 5
              },
              "totpOptions": {
                "digits": 6,
                "period": 30
              },
              "backupCodeOptions": {
                "amount": 10,
                "length": 8
              }
            },
            "hooks": {
              "after": [
                {}
              ]
            },
            "schema": {
              "user": {
                "fields": {
                  "twoFactorEnabled": {
                    "type": "boolean",
                    "required": false,
                    "defaultValue": false,
                    "input": false
                  }
                }
              },
              "twoFactor": {
                "fields": {
                  "secret": {
                    "type": "string",
                    "required": true,
                    "returned": false,
                    "index": true
                  },
                  "backupCodes": {
                    "type": "string",
                    "required": true,
                    "returned": false
                  },
                  "userId": {
                    "type": "string",
                    "required": true,
                    "returned": false,
                    "references": {
                      "model": "user",
                      "field": "id"
                    },
                    "index": true
                  }
                }
              }
            },
            "rateLimit": [
              {
                "window": 10,
                "max": 3
              }
            ],
            "$ERROR_CODES": {
              "OTP_NOT_ENABLED": "OTP not enabled",
              "OTP_HAS_EXPIRED": "OTP has expired",
              "TOTP_NOT_ENABLED": "TOTP not enabled",
              "TWO_FACTOR_NOT_ENABLED": "Two factor isn't enabled",
              "BACKUP_CODES_NOT_ENABLED": "Backup codes aren't enabled",
              "INVALID_BACKUP_CODE": "Invalid backup code",
              "INVALID_CODE": "Invalid code",
              "TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE": "Too many attempts. Please request a new code.",
              "INVALID_TWO_FACTOR_COOKIE": "Invalid two factor cookie"
            }
          }
        },
        {
          "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": "organization",
          "config": {
            "id": "organization",
            "endpoints": {},
            "schema": {
              "organization": {
                "fields": {
                  "name": {
                    "type": "string",
                    "required": true,
                    "sortable": true
                  },
                  "slug": {
                    "type": "string",
                    "required": true,
                    "unique": true,
                    "sortable": true,
                    "index": true
                  },
                  "logo": {
                    "type": "string",
                    "required": false
                  },
                  "createdAt": {
                    "type": "date",
                    "required": true
                  },
                  "metadata": {
                    "type": "string",
                    "required": false
                  }
                }
              },
              "organizationRole": {
                "fields": {
                  "organizationId": {
                    "type": "string",
                    "required": true,
                    "references": {
                      "model": "organization",
                      "field": "id"
                    },
                    "index": true
                  },
                  "role": {
                    "type": "string",
                    "required": true,
                    "index": true
                  },
                  "permission": {
                    "type": "string",
                    "required": true
                  },
                  "createdAt": {
                    "type": "date",
                    "required": true
                  },
                  "updatedAt": {
                    "type": "date",
                    "required": false
                  }
                }
              },
              "team": {
                "fields": {
                  "name": {
                    "type": "string",
                    "required": true
                  },
                  "organizationId": {
                    "type": "string",
                    "required": true,
                    "references": {
                      "model": "organization",
                      "field": "id"
                    },
                    "index": true
                  },
                  "createdAt": {
                    "type": "date",
                    "required": true
                  },
                  "updatedAt": {
                    "type": "date",
                    "required": false
                  }
                }
              },
              "teamMember": {
                "fields": {
                  "teamId": {
                    "type": "string",
                    "required": true,
                    "references": {
                      "model": "team",
                      "field": "id"
                    },
                    "index": true
                  },
                  "userId": {
                    "type": "string",
                    "required": true,
                    "references": {
                      "model": "user",
                      "field": "id"
                    },
                    "index": true
                  },
                  "createdAt": {
                    "type": "date",
                    "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
                  },
                  "teamId": {
                    "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
                  },
                  "activeTeamId": {
                    "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": {
              "teams": {
                "enabled": true,
                "allowRemovingAllTeams": false
              },
              "ac": {
                "statements": {
                  "organization": [
                    "update",
                    "delete"
                  ],
                  "member": [
                    "create",
                    "update",
                    "delete"
                  ],
                  "invitation": [
                    "create",
                    "cancel"
                  ],
                  "team": [
                    "create",
                    "update",
                    "delete"
                  ],
                  "ac": [
                    "create",
                    "read",
                    "update",
                    "delete"
                  ],
                  "project": [
                    "create",
                    "share",
                    "update",
                    "delete"
                  ],
                  "sales": [
                    "view",
                    "create",
                    "edit",
                    "delete"
                  ],
                  "reports": [
                    "view",
                    "generate",
                    "export"
                  ]
                }
              },
              "roles": {
                "owner": {
                  "statements": {
                    "project": [
                      "create",
                      "update",
                      "delete"
                    ]
                  }
                },
                "admin": {
                  "statements": {
                    "project": [
                      "create",
                      "update"
                    ]
                  }
                },
                "member": {
                  "statements": {
                    "project": [
                      "create"
                    ]
                  }
                },
                "myCustomRole": {
                  "statements": {
                    "project": [
                      "create",
                      "update",
                      "delete"
                    ]
                  }
                }
              },
              "dynamicAccessControl": {
                "enabled": true
              }
            }
          }
        },
        {
          "name": "open-api",
          "config": {
            "id": "open-api",
            "endpoints": {}
          }
        },
        {
          "name": "next-cookies",
          "config": {
            "id": "next-cookies",
            "hooks": {
              "after": [
                {}
              ]
            }
          }
        }
      ]
    }
  }
}

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

Package

Auth config (if applicable)

import { sso } from "@better-auth/sso";
import { hashPassword, verifyPassword } from "@packages/auth";
import { resetPasswordEmail } from "@packages/email";
import { db } from "@packages/db";
import * as schema from "@packages/schema";
import { myCustomRole, owner, admin, member } from "@packages/auth";
import { ac } from "./permission";
import { sharedEnv } from "@packages/env";
import { valkeyClient } from "@packages/valkey";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { nextCookies } from "better-auth/next-js";
import { passkey } from "@better-auth/passkey";
import {
  admin as adminPlugin,
  openAPI,
  organization,
  twoFactor,
  lastLoginMethod,
} from "better-auth/plugins";
import { getActiveOrganization } from "./actions/organization/active";
export const auth = betterAuth({
  baseURL: "http://localhost:4321",
  basePath: "/api/auth",
  experimental: { joins: true },
  appName: "Ecom",
  telemetry: {
    enabled: false,
  },
  disabledPaths: [""],
  session: {
    freshAge: 60 * 5,
    expiresIn: 60 * 60 * 24 * 7,
    cookieCache: {
      enabled: true,
      maxAge: 15 * 60,
    },
    storeSessionInDatabase: true,
  },
  rateLimit: {
    enabled: true,
  },
  advanced: {
    ipAddress: {
      ipAddressHeaders: ["cf-connecting-ip", "x-forwarded-for"],
    },
    crossSubDomainCookies: {
      enabled: true,
      domain: "localhost",
    },
    cookiePrefix: sharedEnv.TOKEN_COOKIE_NAME,
    useSecureCookies: true,
  },
  trustedOrigins: ["http://localhost:4321", "http://localhost:3000"],
  user: {
    changeEmail: {
      enabled: true,
      updateEmailWithoutVerification: false,
      sendChangeEmailConfirmation: async (
        { user, newEmail, url, token },
        request,
      ) => {
        console.log(url);
      },
    },
  },
  emailAndPassword: {
    enabled: true,
    autoSignIn: true,
    revokeSessionsOnPasswordReset: true,
    maxPasswordLength: 64,
    minPasswordLength: 8,
    requireEmailVerification: true,
    sendResetPassword: async ({ user, url }) => {
      console.log(url);
    },
    resetPasswordTokenExpiresIn: 1800,
    password: {
      hash: hashPassword,
      verify: verifyPassword,
    },
  },
  emailVerification: {
    autoSignInAfterVerification: true,
    sendOnSignIn: true,
    sendOnSignUp: true,
    expiresIn: 1800,
    sendVerificationEmail: async ({ user, url }, request) => {
      console.log(url);
    },
  },
  account: {
    accountLinking: {
      enabled: true,
    },
  },
  socialProviders: {
    google: {
      clientId: sharedEnv.GOOGLE_CLIENT_ID,
      clientSecret: sharedEnv.GOOGLE_CLIENT_SECRET,
    },
    microsoft: {
      clientId: sharedEnv.MICROSOFT_CLIENT_ID,
      clientSecret: sharedEnv.MICROSOFT_CLIENT_SECRET,
    },
  },
  database: drizzleAdapter(db, {
    provider: "pg",
    schema,
  }),
  secondaryStorage: {
    get: async (key) => {
      try {
        const value = await valkeyClient.get(key);
        return value ?? null;
      } catch (error) {
        console.error("Error getting value from Valkey:", error);
        return null;
      }
    },
    set: async (key, value, ttl) => {
      try {
        if (ttl) await valkeyClient.set(key, value, "EX", ttl);
        else await valkeyClient.set(key, value);
      } catch (error) {
        console.error("Error setting value in Valkey:", error);
        return null;
      }
    },
    delete: async (key) => {
      try {
        await valkeyClient.del(key);
      } catch (error) {
        console.error("Error deleting value from Valkey:", error);
        return null;
      }
    },
  },
  databaseHooks: {
    session: {
      create: {
        before: async (session) => {
          const organization = await getActiveOrganization(session.userId);
          return {
            data: {
              ...session,
              activeOrganizationId: organization?.id,
            },
          };
        },
      },
    },
  },
  plugins: [
    lastLoginMethod({
      storeInDatabase: true,
      cookieName: `${sharedEnv.TOKEN_COOKIE_NAME}.last_used_login_method`,
      maxAge: 60 * 60 * 24 * 60,
    }),
    adminPlugin({}),
    twoFactor({
      otpOptions: {
        async sendOTP({ user, otp }, request) {
          console.log(user, otp);
        },
        period: 3,
        digits: 6,
        allowedAttempts: 5,
      },
      totpOptions: {
        digits: 6,
        period: 30,
      },
      backupCodeOptions: {
        amount: 10,
        length: 8,
      },
    }),
    sso(),
    passkey(),
    organization({
      teams: {
        enabled: true,
        allowRemovingAllTeams: false,
      },
      ac,
      roles: {
        owner,
        admin,
        member,
        myCustomRole,
      },
      dynamicAccessControl: {
        enabled: true,
      },
    }),
    openAPI(),
    nextCookies(),
  ],
});

Additional context

However, adding better auth as serverExternalPackages works.

Originally created by @AmariUwU on GitHub (Dec 15, 2025). Originally assigned to: @himself65 on GitHub. ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. Install better auth in a nextjs 16 project 2. Set up better auth configuration 3. Use better auth in server components (e.g: auth pages) 4. Build with bun runtime: ```bash bun --bun next build ``` 5. Build fails with chunk resolution error ### Current vs. Expected behavior Current behavior: ``` [MDX] generated files in 15.07799ms ▲ Next.js 16.0.10 (Turbopack, Cache Components) - Environments: .env Creating an optimized production build ... ✓ Compiled successfully in 45s ✓ Finished TypeScript in 35.1s Collecting page data using 2 workers ...Error: Failed to load chunk server/chunks/ssr/bb1a9_better-auth_dist_adapters_kysely-adapter_dialect_mjs_7c6a251c._.js from runtime for chunk server/app/(main)/organization/new/page.js at loadRuntimeChunkPath (.next/server/chunks/ssr/[turbopack]_runtime.js:636:19) at loadRuntimeChunk (.next/server/chunks/ssr/[turbopack]_runtime.js:605:9) at c (.next/server/chunks/ssr/[turbopack]_runtime.js:766:25) at <anonymous> (.next/server/app/(main)/organization/new/page.js:21:3) at anonymous (null) at processTicksAndRejections (null) { [cause]: ResolveMessage {} } > Build error occurred Error: Failed to collect page data for /organization/new at processTicksAndRejections (null) { type: 'Error' } error: "next" exited with code 1 error: script "build" exited with code 1 ``` Expected behavior: better auth should build successfully with bun runtime, similar to how it works with node. ### What version of Better Auth are you using? 1.4.6 ### System info ```bash { "system": { "platform": "linux", "arch": "x64", "version": "#1 SMP PREEMPT_DYNAMIC Thu Jun 5 18:30:46 UTC 2025", "release": "6.6.87.2-microsoft-standard-WSL2", "cpuCount": 3, "cpuModel": "Intel(R) Core(TM) i5-10210U CPU @ 1.60GHz", "totalMemory": "7.64 GB", "freeMemory": "4.39 GB" }, "node": { "version": "v24.2.0", "env": "production" }, "packageManager": { "name": "bun", "version": "1.3.5" }, "frameworks": [ { "name": "next", "version": "16.0.10" }, { "name": "react", "version": "^19.2.3" } ], "databases": [ { "name": "pg", "version": "^8.16.3" }, { "name": "drizzle", "version": "^0.45.1" } ], "betterAuth": { "version": "^1.4.6", "config": { "baseURL": "http://localhost:4321", "basePath": "/api/auth", "experimental": { "joins": true }, "appName": "Ecom", "telemetry": { "enabled": false }, "disabledPaths": [ "" ], "session": { "freshAge": 300, "expiresIn": 604800, "cookieCache": { "enabled": true, "maxAge": 900 }, "storeSessionInDatabase": true }, "rateLimit": { "enabled": true }, "advanced": { "ipAddress": { "ipAddressHeaders": [ "cf-connecting-ip", "x-forwarded-for" ] }, "crossSubDomainCookies": { "enabled": true, "domain": "localhost" }, "cookiePrefix": "domain", "useSecureCookies": true }, "trustedOrigins": [ "http://localhost:4321", "http://localhost:3000" ], "user": { "changeEmail": { "enabled": true, "updateEmailWithoutVerification": false } }, "emailAndPassword": { "enabled": true, "autoSignIn": true, "revokeSessionsOnPasswordReset": true, "maxPasswordLength": 64, "minPasswordLength": 8, "requireEmailVerification": true, "resetPasswordTokenExpiresIn": 1800, "password": {} }, "emailVerification": { "autoSignInAfterVerification": true, "sendOnSignIn": true, "sendOnSignUp": true, "expiresIn": 1800 }, "account": { "accountLinking": { "enabled": true } }, "socialProviders": { "google": { "clientId": "[REDACTED]", "clientSecret": "[REDACTED]" }, "microsoft": { "clientId": "[REDACTED]", "clientSecret": "[REDACTED]" } }, "secondaryStorage": {}, "databaseHooks": { "session": { "create": {} } }, "plugins": [ { "name": "last-login-method", "config": { "id": "last-login-method", "hooks": { "after": [ {} ] }, "schema": { "user": { "fields": { "lastLoginMethod": { "type": "string", "input": false, "required": false, "fieldName": "lastLoginMethod" } } } } } }, { "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", "YOU_CANNOT_IMPERSONATE_ADMINS": "You cannot impersonate admins", "INVALID_ROLE_TYPE": "Invalid role type" }, "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 } } } }, "options": {} } }, { "name": "two-factor", "config": { "id": "two-factor", "endpoints": {}, "options": { "otpOptions": { "period": 3, "digits": 6, "allowedAttempts": 5 }, "totpOptions": { "digits": 6, "period": 30 }, "backupCodeOptions": { "amount": 10, "length": 8 } }, "hooks": { "after": [ {} ] }, "schema": { "user": { "fields": { "twoFactorEnabled": { "type": "boolean", "required": false, "defaultValue": false, "input": false } } }, "twoFactor": { "fields": { "secret": { "type": "string", "required": true, "returned": false, "index": true }, "backupCodes": { "type": "string", "required": true, "returned": false }, "userId": { "type": "string", "required": true, "returned": false, "references": { "model": "user", "field": "id" }, "index": true } } } }, "rateLimit": [ { "window": 10, "max": 3 } ], "$ERROR_CODES": { "OTP_NOT_ENABLED": "OTP not enabled", "OTP_HAS_EXPIRED": "OTP has expired", "TOTP_NOT_ENABLED": "TOTP not enabled", "TWO_FACTOR_NOT_ENABLED": "Two factor isn't enabled", "BACKUP_CODES_NOT_ENABLED": "Backup codes aren't enabled", "INVALID_BACKUP_CODE": "Invalid backup code", "INVALID_CODE": "Invalid code", "TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE": "Too many attempts. Please request a new code.", "INVALID_TWO_FACTOR_COOKIE": "Invalid two factor cookie" } } }, { "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": "organization", "config": { "id": "organization", "endpoints": {}, "schema": { "organization": { "fields": { "name": { "type": "string", "required": true, "sortable": true }, "slug": { "type": "string", "required": true, "unique": true, "sortable": true, "index": true }, "logo": { "type": "string", "required": false }, "createdAt": { "type": "date", "required": true }, "metadata": { "type": "string", "required": false } } }, "organizationRole": { "fields": { "organizationId": { "type": "string", "required": true, "references": { "model": "organization", "field": "id" }, "index": true }, "role": { "type": "string", "required": true, "index": true }, "permission": { "type": "string", "required": true }, "createdAt": { "type": "date", "required": true }, "updatedAt": { "type": "date", "required": false } } }, "team": { "fields": { "name": { "type": "string", "required": true }, "organizationId": { "type": "string", "required": true, "references": { "model": "organization", "field": "id" }, "index": true }, "createdAt": { "type": "date", "required": true }, "updatedAt": { "type": "date", "required": false } } }, "teamMember": { "fields": { "teamId": { "type": "string", "required": true, "references": { "model": "team", "field": "id" }, "index": true }, "userId": { "type": "string", "required": true, "references": { "model": "user", "field": "id" }, "index": true }, "createdAt": { "type": "date", "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 }, "teamId": { "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 }, "activeTeamId": { "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": { "teams": { "enabled": true, "allowRemovingAllTeams": false }, "ac": { "statements": { "organization": [ "update", "delete" ], "member": [ "create", "update", "delete" ], "invitation": [ "create", "cancel" ], "team": [ "create", "update", "delete" ], "ac": [ "create", "read", "update", "delete" ], "project": [ "create", "share", "update", "delete" ], "sales": [ "view", "create", "edit", "delete" ], "reports": [ "view", "generate", "export" ] } }, "roles": { "owner": { "statements": { "project": [ "create", "update", "delete" ] } }, "admin": { "statements": { "project": [ "create", "update" ] } }, "member": { "statements": { "project": [ "create" ] } }, "myCustomRole": { "statements": { "project": [ "create", "update", "delete" ] } } }, "dynamicAccessControl": { "enabled": true } } } }, { "name": "open-api", "config": { "id": "open-api", "endpoints": {} } }, { "name": "next-cookies", "config": { "id": "next-cookies", "hooks": { "after": [ {} ] } } } ] } } } ``` ### Which area(s) are affected? (Select all that apply) Package ### Auth config (if applicable) ```typescript import { sso } from "@better-auth/sso"; import { hashPassword, verifyPassword } from "@packages/auth"; import { resetPasswordEmail } from "@packages/email"; import { db } from "@packages/db"; import * as schema from "@packages/schema"; import { myCustomRole, owner, admin, member } from "@packages/auth"; import { ac } from "./permission"; import { sharedEnv } from "@packages/env"; import { valkeyClient } from "@packages/valkey"; import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { nextCookies } from "better-auth/next-js"; import { passkey } from "@better-auth/passkey"; import { admin as adminPlugin, openAPI, organization, twoFactor, lastLoginMethod, } from "better-auth/plugins"; import { getActiveOrganization } from "./actions/organization/active"; export const auth = betterAuth({ baseURL: "http://localhost:4321", basePath: "/api/auth", experimental: { joins: true }, appName: "Ecom", telemetry: { enabled: false, }, disabledPaths: [""], session: { freshAge: 60 * 5, expiresIn: 60 * 60 * 24 * 7, cookieCache: { enabled: true, maxAge: 15 * 60, }, storeSessionInDatabase: true, }, rateLimit: { enabled: true, }, advanced: { ipAddress: { ipAddressHeaders: ["cf-connecting-ip", "x-forwarded-for"], }, crossSubDomainCookies: { enabled: true, domain: "localhost", }, cookiePrefix: sharedEnv.TOKEN_COOKIE_NAME, useSecureCookies: true, }, trustedOrigins: ["http://localhost:4321", "http://localhost:3000"], user: { changeEmail: { enabled: true, updateEmailWithoutVerification: false, sendChangeEmailConfirmation: async ( { user, newEmail, url, token }, request, ) => { console.log(url); }, }, }, emailAndPassword: { enabled: true, autoSignIn: true, revokeSessionsOnPasswordReset: true, maxPasswordLength: 64, minPasswordLength: 8, requireEmailVerification: true, sendResetPassword: async ({ user, url }) => { console.log(url); }, resetPasswordTokenExpiresIn: 1800, password: { hash: hashPassword, verify: verifyPassword, }, }, emailVerification: { autoSignInAfterVerification: true, sendOnSignIn: true, sendOnSignUp: true, expiresIn: 1800, sendVerificationEmail: async ({ user, url }, request) => { console.log(url); }, }, account: { accountLinking: { enabled: true, }, }, socialProviders: { google: { clientId: sharedEnv.GOOGLE_CLIENT_ID, clientSecret: sharedEnv.GOOGLE_CLIENT_SECRET, }, microsoft: { clientId: sharedEnv.MICROSOFT_CLIENT_ID, clientSecret: sharedEnv.MICROSOFT_CLIENT_SECRET, }, }, database: drizzleAdapter(db, { provider: "pg", schema, }), secondaryStorage: { get: async (key) => { try { const value = await valkeyClient.get(key); return value ?? null; } catch (error) { console.error("Error getting value from Valkey:", error); return null; } }, set: async (key, value, ttl) => { try { if (ttl) await valkeyClient.set(key, value, "EX", ttl); else await valkeyClient.set(key, value); } catch (error) { console.error("Error setting value in Valkey:", error); return null; } }, delete: async (key) => { try { await valkeyClient.del(key); } catch (error) { console.error("Error deleting value from Valkey:", error); return null; } }, }, databaseHooks: { session: { create: { before: async (session) => { const organization = await getActiveOrganization(session.userId); return { data: { ...session, activeOrganizationId: organization?.id, }, }; }, }, }, }, plugins: [ lastLoginMethod({ storeInDatabase: true, cookieName: `${sharedEnv.TOKEN_COOKIE_NAME}.last_used_login_method`, maxAge: 60 * 60 * 24 * 60, }), adminPlugin({}), twoFactor({ otpOptions: { async sendOTP({ user, otp }, request) { console.log(user, otp); }, period: 3, digits: 6, allowedAttempts: 5, }, totpOptions: { digits: 6, period: 30, }, backupCodeOptions: { amount: 10, length: 8, }, }), sso(), passkey(), organization({ teams: { enabled: true, allowRemovingAllTeams: false, }, ac, roles: { owner, admin, member, myCustomRole, }, dynamicAccessControl: { enabled: true, }, }), openAPI(), nextCookies(), ], }); ``` ### Additional context However, adding better auth as serverExternalPackages works.
GiteaMirror added the nextjsbug labels 2026-03-13 10:01:41 -05:00
Author
Owner

@better-auth-agent[bot] commented on GitHub (Dec 15, 2025):

tag @better-auth-agent if you would like an answer from the Agent

If you need more help, tag @better-auth-agent in a comment so I can respond.

DiagramDiscordGitHub

Diagram Join Star

@better-auth-agent[bot] commented on GitHub (Dec 15, 2025): tag @better-auth-agent if you would like an answer from the Agent _If you need more help, tag @better-auth-agent in a comment so I can respond._ <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) • [Discord](https://discord.gg/fG2XXEuQX3) • [GitHub](https://github.com/Skyvern-AI/Skyvern) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/fG2XXEuQX3) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/Skyvern-AI/Skyvern)
Author
Owner

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

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

This build failure happens because Better Auth's Kysely adapter uses dynamic imports and Node.js-specific modules (like node:sqlite) that Bun and Turbopack can't resolve or bundle properly in Next.js 16. The chunk resolution error is triggered when the bundler tries to process these Node-only modules, which aren't available or supported in the Bun runtime or Turbopack's chunking context see details.

Adding Better Auth as serverExternalPackages works because it tells the bundler to treat it as an external dependency, so it doesn't try to bundle or resolve those problematic imports reference. This is currently the recommended workaround for Bun + Next.js 16.

If you run into similar issues, make sure:

  • You only import Better Auth server code in server components (never in client components).
  • You use granular imports (not just import { ... } from "better-auth" everywhere).
  • You keep your Better Auth and Next.js versions up to date, as compatibility is still evolving reference.

Right now, marking Better Auth as serverExternalPackages is the best way to avoid these build errors with Bun and Next.js 16.

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

@dosubot[bot] commented on GitHub (Dec 15, 2025): <!-- Greeting --> Hi @AmariUwU! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> This build failure happens because Better Auth's Kysely adapter uses dynamic imports and Node.js-specific modules (like `node:sqlite`) that Bun and Turbopack can't resolve or bundle properly in Next.js 16. The chunk resolution error is triggered when the bundler tries to process these Node-only modules, which aren't available or supported in the Bun runtime or Turbopack's chunking context [see details](https://github.com/better-auth/better-auth/blob/a63e70ea27e2e936ae9915171c0e59054dc9b4a0/packages/better-auth/src/adapters/kysely-adapter/dialect.ts#L107-L140). Adding Better Auth as `serverExternalPackages` works because it tells the bundler to treat it as an external dependency, so it doesn't try to bundle or resolve those problematic imports [reference](https://github.com/better-auth/better-auth/issues/6668). This is currently the recommended workaround for Bun + Next.js 16. If you run into similar issues, make sure: - You only import Better Auth server code in server components (never in client components). - You use granular imports (not just `import { ... } from "better-auth"` everywhere). - You keep your Better Auth and Next.js versions up to date, as compatibility is still evolving [reference](https://github.com/better-auth/better-auth/issues/5263). Right now, marking Better Auth as `serverExternalPackages` is the best way to avoid these build errors with Bun and Next.js 16. <!-- 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/190fd4b9-cf98-43f6-9252-9d1e82f4ba51?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/190fd4b9-cf98-43f6-9252-9d1e82f4ba51?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/190fd4b9-cf98-43f6-9252-9d1e82f4ba51?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/190fd4b9-cf98-43f6-9252-9d1e82f4ba51?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/190fd4b9-cf98-43f6-9252-9d1e82f4ba51?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/190fd4b9-cf98-43f6-9252-9d1e82f4ba51?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/190fd4b9-cf98-43f6-9252-9d1e82f4ba51?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%20build%20failure%20happens%20because%20Better%20Auth%27s%20Kysely%20adapter%20uses%20dynamic%20imports%20and%20Node.js-specific%20modules%20%28like%20%60node%3Asqlite%60%29%20that%20Bun%20and%20Turbopack%20can%27t%20resolve%20or%20bundle%20properly%20in%20Next.js%2016.%20The%20chunk%20resolution%20error%20is%20triggered%20when%20the%20bundler%20tries%20to%20process%20these%20Node-only%20modules%2C%20which%20aren%27t%20available%20or%20supported%20in%20the%20Bun%20runtime%20or%20Turbopack%27s%20chunking%20context%C2%A0%5Bsee%20details%5D%28https%3A//github.com/better-auth/better-auth/blob/a63e70ea27e2e936ae9915171c0e59054dc9b4a0/packages/better-auth/src/adapters/kysely-adapter/dialect.ts%23L107-L140%29.%0A%0AAdding%20Better%20Auth%20as%20%60serverExternalPackages%60%20works%20because%20it%20tells%20the%20bundler%20to%20treat%20it%20as%20an%20external%20dependency%2C%20so%20it%20doesn%27t%20try%20to%20bundle%20or%20resolve%20those%20problematic%20imports%C2%A0%5Breference%5D%28https%3A//github.com/better-auth/better-auth/issues/6668%29.%20This%20is%20currently%20the%20recommended%20workaround%20for%20Bun%20%2B%20Next.js%2016.%0A%0AIf%20you%20run%20into%20similar%20issues%2C%20make%20sure%3A%0A-%20You%20only%20import%20Better%20Auth%20server%20code%20in%20server%20components%20%28never%20in%20client%20components%29.%0A-%20You%20use%20granular%20imports%20%28not%20just%20%60import%20%7B%20...%20%7D%20from%20%22better-auth%22%60%20everywhere%29.%0A-%20You%20keep%20your%20Better%20Auth%20and%20Next.js%20versions%20up%20to%20date%2C%20as%20compatibility%20is%20still%20evolving%C2%A0%5Breference%5D%28https%3A//github.com/better-auth/better-auth/issues/5263%29.%0A%0ARight%20now%2C%20marking%20Better%20Auth%20as%20%60serverExternalPackages%60%20is%20the%20best%20way%20to%20avoid%20these%20build%20errors%20with%20Bun%20and%20Next.js%2016.)&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/6781)
Author
Owner

@himself65 commented on GitHub (Dec 16, 2025):

Could you please show a reproducible repo? It might be a bunjs issue, not us

@himself65 commented on GitHub (Dec 16, 2025): Could you please show a reproducible repo? It might be a bunjs issue, not us
Author
Owner

@AmariUwU commented on GitHub (Dec 17, 2025):

@himself65
https://github.com/AmariUwU/better-auth-bun

@AmariUwU commented on GitHub (Dec 17, 2025): @himself65 https://github.com/AmariUwU/better-auth-bun
Author
Owner

@marcelloinfoweb commented on GitHub (Feb 20, 2026):

+1

@marcelloinfoweb commented on GitHub (Feb 20, 2026): +1
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#2542