{"record":{"id":"4b8bfd4e1cb3d12f","repo":"mastra-ai/mastra","slug":"mastraauthbetterauth-is-not-initialized-init-m","errorCode":null,"errorMessage":"MastraAuthBetterAuth is not initialized — init() must run first (or pass a configured `auth` instance).","messagePattern":"MastraAuthBetterAuth is not initialized — init\\(\\) must run first \\(or pass a configured `auth` instance\\)\\.","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"auth/better-auth/src/index.ts","lineNumber":233,"sourceCode":"        'Better Auth instance is required. Please provide the auth option with your Better Auth instance created via betterAuth({ ... }), ' +\n          'or provide `secret` so the provider can build its own instance in init() on the host database.',\n      );\n    }\n\n    this.#auth = options.auth;\n    this.#secret = options.secret;\n    this.signUpEnabledConfig = options.signUpEnabled ?? true;\n\n    this.registerOptions(options);\n  }\n\n  /**\n   * The active Better Auth instance. Throws before `init()` in deferred\n   * instance mode (constructed with `secret` instead of `auth`).\n   */\n  protected get auth(): Auth {\n    if (!this.#auth) {\n      throw new Error(\n        'MastraAuthBetterAuth is not initialized — init() must run first (or pass a configured `auth` instance).',\n      );\n    }\n    return this.#auth;\n  }\n\n  /**\n   * Session cookie name, honoring Better Auth's `cookiePrefix`, a caller\n   * override via `advanced.cookies.session_token.name`, and the `__Secure-`\n   * prefix Better Auth applies when secure cookies are active.\n   */\n  get sessionCookieName(): string {\n    const options = (this.#auth as { options?: { baseURL?: string; advanced?: Record<string, unknown> } } | undefined)\n      ?.options;\n    const advanced = options?.advanced as\n      | {\n          cookiePrefix?: string;\n          useSecureCookies?: boolean;","sourceCodeStart":215,"sourceCodeEnd":251,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/auth/better-auth/src/index.ts#L215-L251","documentation":"This error comes from the protected `auth` getter, which lazily returns the active Better Auth instance. In deferred mode (constructed with `secret` instead of `auth`), the instance is only created when init() runs during host startup; calling auth-dependent methods before that leaves this.#auth undefined and the getter throws.","triggerScenarios":"Calling any MastraAuthBetterAuth public method that touches the `auth` getter (signIn, signUp, session/user lookups, etc.) after `new MastraAuthBetterAuth({ secret })` but before the host framework invokes init(ctx); or in deferred mode with an init() that never ran because the provider wasn't registered with the host.","commonSituations":"Unit tests instantiating the provider directly and calling methods without simulating host init; wiring the provider outside the Mastra server bootstrap so init(ctx) is never called; calling auth APIs in a top-level module executed before server startup.","solutions":["Ensure the provider is registered with the Mastra server so init(ctx) runs before any request handling.","Pass a fully configured Better Auth instance instead of relying on deferred init: new MastraAuthBetterAuth({ auth: betterAuth({...}) }).","In tests, call init(ctx) manually with a suitable AuthInitContext (including database) before exercising auth methods."],"exampleFix":"// before: deferred mode, methods called before host init\nconst provider = new MastraAuthBetterAuth({ secret: process.env.BETTER_AUTH_SECRET });\nawait provider.signIn({ email, password }); // throws\n\n// after: pass configured instance so auth is available immediately\nconst provider = new MastraAuthBetterAuth({\n  auth: betterAuth({ database: myDb, secret: process.env.BETTER_AUTH_SECRET }),\n});\nawait provider.signIn({ email, password });","handlingStrategy":"validation","validationCode":"// ensure host init ran before using deferred-mode provider\nif (!providerIsInitialized(provider)) {\n  await provider.init({ database: authDatabase, allowedOrigins: serverOrigins });\n}","typeGuard":"function isAuthReady(p: MastraAuthBetterAuth): boolean {\n  // deferred-mode providers are usable only after init(); prefer bring-your-own mode to guarantee readiness\n  return 'auth' in p; // or track an initialized flag in your wiring layer\n}","tryCatchPattern":"try {\n  await provider.signIn({ email, password });\n} catch (e) {\n  if (e instanceof Error && e.message.includes('not initialized')) {\n    throw new Error('Server bootstrap bug: MastraAuthBetterAuth.init() did not run before request handling', { cause: e });\n  }\n  throw e;\n}","preventionTips":["Prefer passing a configured `auth` instance over deferred `secret` mode when you control construction.","Register the provider through the Mastra server bootstrap so init(ctx) always runs before traffic.","In integration tests, call init(ctx) in beforeAll before exercising auth methods."],"tags":["lifecycle","better-auth","initialization-order","async"],"backgroundTag":"not-initialized-before-use","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T08:17:16.595Z"}