mastra-ai/mastra · error

MastraAuthBetterAuth is not initialized — init() must run fi

Error message

MastraAuthBetterAuth is not initialized — init() must run first (or pass a configured `auth` instance).

What it means

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.

Source

Thrown at auth/better-auth/src/index.ts:233

        'Better Auth instance is required. Please provide the auth option with your Better Auth instance created via betterAuth({ ... }), ' +
          'or provide `secret` so the provider can build its own instance in init() on the host database.',
      );
    }

    this.#auth = options.auth;
    this.#secret = options.secret;
    this.signUpEnabledConfig = options.signUpEnabled ?? true;

    this.registerOptions(options);
  }

  /**
   * The active Better Auth instance. Throws before `init()` in deferred
   * instance mode (constructed with `secret` instead of `auth`).
   */
  protected get auth(): Auth {
    if (!this.#auth) {
      throw new Error(
        'MastraAuthBetterAuth is not initialized — init() must run first (or pass a configured `auth` instance).',
      );
    }
    return this.#auth;
  }

  /**
   * Session cookie name, honoring Better Auth's `cookiePrefix`, a caller
   * override via `advanced.cookies.session_token.name`, and the `__Secure-`
   * prefix Better Auth applies when secure cookies are active.
   */
  get sessionCookieName(): string {
    const options = (this.#auth as { options?: { baseURL?: string; advanced?: Record<string, unknown> } } | undefined)
      ?.options;
    const advanced = options?.advanced as
      | {
          cookiePrefix?: string;
          useSecureCookies?: boolean;

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Ensure the provider is registered with the Mastra server so init(ctx) runs before any request handling.
  2. Pass a fully configured Better Auth instance instead of relying on deferred init: new MastraAuthBetterAuth({ auth: betterAuth({...}) }).
  3. In tests, call init(ctx) manually with a suitable AuthInitContext (including database) before exercising auth methods.

Example fix

// before: deferred mode, methods called before host init
const provider = new MastraAuthBetterAuth({ secret: process.env.BETTER_AUTH_SECRET });
await provider.signIn({ email, password }); // throws

// after: pass configured instance so auth is available immediately
const provider = new MastraAuthBetterAuth({
  auth: betterAuth({ database: myDb, secret: process.env.BETTER_AUTH_SECRET }),
});
await provider.signIn({ email, password });
Defensive patterns

Strategy: validation

Validate before calling

// ensure host init ran before using deferred-mode provider
if (!providerIsInitialized(provider)) {
  await provider.init({ database: authDatabase, allowedOrigins: serverOrigins });
}

Type guard

function isAuthReady(p: MastraAuthBetterAuth): boolean {
  // deferred-mode providers are usable only after init(); prefer bring-your-own mode to guarantee readiness
  return 'auth' in p; // or track an initialized flag in your wiring layer
}

Try / catch

try {
  await provider.signIn({ email, password });
} catch (e) {
  if (e instanceof Error && e.message.includes('not initialized')) {
    throw new Error('Server bootstrap bug: MastraAuthBetterAuth.init() did not run before request handling', { cause: e });
  }
  throw e;
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/4b8bfd4e1cb3d12f. Report an issue: GitHub.