Files
skills/docs/api-stack/api/api-auth-better-auth/src/oauth/default-factory.md
2026-05-29 08:20:56 +01:00

2.8 KiB

default-factory

Purpose

Default betterAuthFactory used when an operator does not supply one via BetterAuthOptions.betterAuthFactory. Dynamically imports better-auth AND (when OAuth providers are configured) the genericOAuth plugin, then calls betterAuth({...}) with the assembled args. The dynamic imports mean module-load of @suaveplan/api-auth-better-auth never blocks on better-auth — operators that ship a stubbed factory (unit tests, custom adapter shells) avoid the upstream package altogether.

Features

  • Dynamic import("better-auth") keeps cold-start fast for stub-only consumers.
  • Dynamic import("better-auth/plugins/generic-oauth") only fires when the options actually configure OAuth providers.
  • The Suaveplan-private __suaveplan_generic_oauth sentinel key from buildBetterAuthFactoryArgs is stripped before forwarding so the upstream package never sees our internal fields.
  • Pre-existing plugins arrays the operator may pass through their own factory are preserved (the genericOAuth plugin is appended, not assigned).

Usage: Basic

// Production wiring — pass options without a betterAuthFactory and the
// default fires implicitly:
const provider = createBetterAuthProvider({
    database: pool,
    baseUrl: "https://api.example.com",
    secret: process.env.BETTER_AUTH_SECRET!,
});

Usage: Advanced

import { defaultBetterAuthFactory } from "@suaveplan/api-auth-better-auth";

// Operator-supplied factory that wraps the default to inject the
// `organization` Better-Auth plugin on top of whatever the wrapper itself
// already configures:
const customFactory = async (args: Record<string, unknown>) => {
    const auth = await defaultBetterAuthFactory(args);
    return auth;
};

const provider = createBetterAuthProvider({
    database: pool,
    baseUrl,
    secret,
    betterAuthFactory: customFactory,
});

API Reference

Export Shape Purpose
defaultBetterAuthFactory(args) (Record<string, unknown>) => Promise<BetterAuthLike> Dynamic loader + plugin assembler

Implementation Notes

The sentinel-key pattern (__suaveplan_generic_oauth) is the trade-off between (a) keeping buildBetterAuthFactoryArgs synchronous and pure, and (b) actually loading the upstream plugin module. The args bag is built synchronously so callers and tests can inspect it; the plugin module is loaded lazily inside this factory. Stripping the sentinel keeps the boundary clean — Better-Auth's option validator complains about unknown top-level keys.

The plugins array preservation matters because operators MAY supply a custom factory that adds Better-Auth's own plugins (organisation, passkeys, 2FA, magic-link) on top of the OAuth config the wrapper itself injects. By appending we ensure a stub operator factory + the wrapper's genericOAuth config coexist correctly.