GitHub
Menu

API Reference

@kovojs/better-auth

Generated from packages/better-auth/src/index.ts — 34 exports, 34 documented. Do not edit by hand.

Functions#

betterAuthSession#

Builds a Kovo SessionProvider backed by Better Auth: it calls auth.api.getSession({ headers }) for each request and projects the result through map into the app's session value, returning null when there is no session. Wire the returned provider into session(...) so guards and pages see the authenticated user (SPEC.md §6.5).

ts
function betterAuthSession<
  AuthSession,
  AuthUser,
  SessionValue,
  Request extends BetterAuthRequestLike = BetterAuthRequestLike,
>(
  auth: BetterAuthLike<AuthSession, AuthUser>,
  map: BetterAuthSessionMapper<AuthSession, AuthUser, SessionValue>,
): SessionProvider<Request, SessionValue>;

mount#

Mounts Better Auth's own request handler at a prefix endpoint so its browser redirect protocol — OAuth/SAML/magic-link callbacks and similar provider round-trips — is served under one declared path, while credential forms stay on typed mutations (SPEC.md §9.1).

SECURITY — this endpoint is always declared with csrf: false. Per SPEC.md §6.6, CSRF protection is default-ON for server-rendered, cookie-authenticated mutations, and csrf: false is the framework's sanctioned opt-out reserved for endpoints that are not browser-form-driven or are authenticated by some other means (e.g. non-browser / externally-authenticated callers). Better Auth's redirect protocol handler is exactly such an endpoint: the inbound requests are external-provider redirects and the library-supplied OAuth state parameter (not a Kovo CSRF token) carries the anti-forgery guarantee, so a Kovo CSRF token cannot be present or required here. Disabling CSRF on this prefix does NOT relax protection on the app's own credential mutations, which keep CSRF on. The reason is recorded on the endpoint via csrfJustification (overridable through BetterAuthMountOptions).

ts
function mount<
  const Path extends string,
  const Method extends EndpointMethod = EndpointMethod,
>(
  path: Path,
  auth: BetterAuthMountLike | BetterAuthMountHandler,
  options: BetterAuthMountOptions<Method> = {},
): EndpointDeclaration<Path, Method, 'prefix'>;

betterAuthSignInEmailMutation#

Builds a typed Kovo mutation that signs a user in via Better Auth email/password. Calls auth.api.signInEmail with asResponse: true, treats the result as success only on POSITIVE evidence of an established session (2xx, no two-factor-pending body, and a session-establishing Set-Cookie), forwards the session cookie, and otherwise returns the declared INVALID_CREDENTIALS failure. Defaults the mutation key to auth/sign-in. Wire it into the app's mutation registry and pair it with a CSRF-protected login form (SPEC.md §6.5; CSRF default-on per §6.6).

ts
function betterAuthSignInEmailMutation<
  const Key extends string = 'auth/sign-in',
  Request extends BetterAuthRequestLike = BetterAuthRequestLike,
  GuardedRequest extends Request = Request,
>(
  auth: BetterAuthSignInEmailLike,
  options: BetterAuthCredentialMutationOptions<Key, Request, GuardedRequest> = {},
): MutationDefinition<
  Key,
  typeof betterAuthSignInEmailInput,
  typeof betterAuthCredentialMutationErrors,
  Request,
  BetterAuthCredentialMutationValue<'signed-in'>,
  GuardedRequest
> & { key: Key };

betterAuthSignUpEmailMutation#

Builds a typed Kovo mutation that registers a user via Better Auth email/password. Calls auth.api.signUpEmail with asResponse: true, applies the same positive-session-evidence success check as sign-in, forwards the session cookie, and returns the declared INVALID_CREDENTIALS failure otherwise. Defaults the mutation key to auth/sign-up (SPEC.md §6.5; CSRF default-on per §6.6).

ts
function betterAuthSignUpEmailMutation<
  const Key extends string = 'auth/sign-up',
  Request extends BetterAuthRequestLike = BetterAuthRequestLike,
  GuardedRequest extends Request = Request,
>(
  auth: BetterAuthSignUpEmailLike,
  options: BetterAuthCredentialMutationOptions<Key, Request, GuardedRequest> = {},
): MutationDefinition<
  Key,
  typeof betterAuthSignUpEmailInput,
  typeof betterAuthCredentialMutationErrors,
  Request,
  BetterAuthCredentialMutationValue<'signed-up'>,
  GuardedRequest
> & { key: Key };

betterAuthSignOutMutation#

Builds a typed Kovo mutation that signs a user out via Better Auth. Calls auth.api.signOut with asResponse: true, forwards the session-clearing Set-Cookie headers into the mutation response, and redirects to defaultRedirectTo (default /login). Defaults the mutation key to auth/sign-out. Typically guarded so only an authenticated request can sign out (SPEC.md §6.5; CSRF default-on per §6.6).

ts
function betterAuthSignOutMutation<
  const Key extends string = 'auth/sign-out',
  Request extends BetterAuthRequestLike = BetterAuthRequestLike,
  GuardedRequest extends Request = Request,
>(
  auth: BetterAuthSignOutLike,
  options: BetterAuthCredentialMutationOptions<Key, Request, GuardedRequest> = {},
): MutationDefinition<
  Key,
  typeof betterAuthSignOutInput,
  Record<string, never>,
  Request,
  BetterAuthCredentialMutationValue<'signed-out'>,
  GuardedRequest
> & { key: Key };

authed#

Guard that requires an authenticated session, narrowing the request to an AuthenticatedRequest. A thin re-export of the framework's guards.authed for use on auth-protected mutations and routes; an unauthenticated request denies with a login-redirect intent (SPEC.md §6.5).

ts
function authed<Request extends SessionRequestLike>(): Guard<
  Request,
  AuthenticatedRequest<Request>
>;

role#

Guard that requires the session user to hold a given role. Denies with an unauthenticated (→ login redirect) intent when there is no session user, and with a forbidden (→ 403) intent when the user lacks the role. The role name is type-checked against the request's own roles element type when known (SPEC.md §6.5).

ts
function role<Request extends BetterAuthRoleRequest>(
  requiredRole: RoleNameFor<Request>,
): Guard<Request>;
function role(requiredRole: string): Guard<BetterAuthRoleRequest>;

Types & interfaces#

BetterAuthGetSessionOptions#

Options passed to a Better Auth getSession call. Carries the incoming request Headers so Better Auth can read the session cookie. Part of the BetterAuthApi contract the adapter consumes when building a Kovo session provider (SPEC.md §6.5).

ts
interface BetterAuthGetSessionOptions {
  headers: Headers;
}

BetterAuthSessionPayload#

The { session, user } pair Better Auth returns for an authenticated request. The adapter maps this into the app's own session value via a BetterAuthSessionMapper; see SPEC.md §6.5 for how sessions flow into the request.

ts
interface BetterAuthSessionPayload<Session, User> {
  session: Session;
  user: User;
}

BetterAuthApi#

The subset of the Better Auth server api the session provider depends on: a getSession method returning a BetterAuthSessionPayload (or null/undefined when unauthenticated). Structurally satisfied by a real Better Auth instance.

ts
interface BetterAuthApi<Session, User> {
  getSession(
    options: BetterAuthGetSessionOptions,
  ): MaybePromise<BetterAuthSessionPayload<Session, User> | null | undefined>;
}

BetterAuthLike#

Structural shape of a Better Auth instance accepted by betterAuthSession: it just needs an api exposing getSession. Apps pass their real Better Auth object, which satisfies this without an explicit cast (SPEC.md §6.5).

ts
interface BetterAuthLike<Session, User> {
  api: BetterAuthApi<Session, User>;
}

BetterAuthRequestLike#

Minimal request shape the credential mutations and session provider read from: an object carrying the incoming Headers. Apps extend this with their own session and CSRF fields; it is the default Request type parameter across this adapter's helpers.

ts
interface BetterAuthRequestLike {
  headers: Headers;
}

BetterAuthMountHandler#

Handler that turns a web Request into a Response. This is Better Auth's own fetch-style handler, mounted at a prefix endpoint by mount to serve the library's browser redirect protocol (OAuth/SAML/magic-link callbacks; SPEC.md §9.1).

ts
type BetterAuthMountHandler = (request: Request) => MaybePromise<Response>;

BetterAuthMountLike#

Structural shape of a Better Auth instance accepted by mount: it just needs a handler. Apps pass their real Better Auth object directly.

ts
interface BetterAuthMountLike {
  handler: BetterAuthMountHandler;
}

BetterAuthMountOptions#

Options for mount. auth overrides the default custom endpoint auth declaration; method narrows the HTTP method; csrfJustification records why this prefix endpoint is exempt from CSRF (the endpoint always runs with csrf: false — see mount for the SPEC.md §6.6 rationale).

ts
interface BetterAuthMountOptions<Method extends EndpointMethod = EndpointMethod> {
  auth?: EndpointAuthDeclaration;
  csrfJustification?: string;
  method?: Method;
}

BetterAuthSessionMapper#

Function the app supplies to betterAuthSession to project Better Auth's { session, user } payload into the app's own session value. Called once per authenticated request (SPEC.md §6.5).

ts
type BetterAuthSessionMapper<AuthSession, AuthUser, SessionValue> = (
  value: BetterAuthSessionPayload<AuthSession, AuthUser>,
) => SessionValue;

BetterAuthResponseLike#

Minimal Better Auth response shape the credential mutations inspect: an object with status and headers. Used to classify sign-in/sign-up success and to forward Set-Cookie headers into the mutation response (SPEC.md §6.5).

ts
interface BetterAuthResponseLike {
  headers: Headers;
  status: number;
}

BetterAuthSignInEmailBody#

Request body for a Better Auth email/password sign-in: email and password.

ts
interface BetterAuthSignInEmailBody {
  email: string;
  password: string;
}

BetterAuthSignUpEmailBody#

Request body for a Better Auth email/password sign-up: a sign-in body plus name.

ts
interface BetterAuthSignUpEmailBody extends BetterAuthSignInEmailBody {
  name: string;
}

BetterAuthSignInEmailApi#

The subset of the Better Auth server api consumed by betterAuthSignInEmailMutation: a signInEmail method invoked with asResponse: true so the adapter can read the raw response status and Set-Cookie headers (SPEC.md §6.5).

ts
interface BetterAuthSignInEmailApi {
  signInEmail(options: {
    asResponse: true;
    body: BetterAuthSignInEmailBody;
    headers: Headers;
  }): MaybePromise<BetterAuthResponseLike>;
}

BetterAuthSignUpEmailApi#

The subset of the Better Auth server api consumed by betterAuthSignUpEmailMutation: a signUpEmail method invoked with asResponse: true (SPEC.md §6.5).

ts
interface BetterAuthSignUpEmailApi {
  signUpEmail(options: {
    asResponse: true;
    body: BetterAuthSignUpEmailBody;
    headers: Headers;
  }): MaybePromise<BetterAuthResponseLike>;
}

BetterAuthSignOutApi#

The subset of the Better Auth server api consumed by betterAuthSignOutMutation: a signOut method invoked with asResponse: true so the session-clearing Set-Cookie headers can be forwarded (SPEC.md §6.5).

ts
interface BetterAuthSignOutApi {
  signOut(options: { asResponse: true; headers: Headers }): MaybePromise<BetterAuthResponseLike>;
}

BetterAuthSignInEmailLike#

Structural shape accepted by betterAuthSignInEmailMutation: a Better Auth instance whose api exposes signInEmail. A real Better Auth object satisfies this.

ts
interface BetterAuthSignInEmailLike {
  api: BetterAuthSignInEmailApi;
}

BetterAuthSignUpEmailLike#

Structural shape accepted by betterAuthSignUpEmailMutation: a Better Auth instance whose api exposes signUpEmail.

ts
interface BetterAuthSignUpEmailLike {
  api: BetterAuthSignUpEmailApi;
}

BetterAuthSignOutLike#

Structural shape accepted by betterAuthSignOutMutation: a Better Auth instance whose api exposes signOut.

ts
interface BetterAuthSignOutLike {
  api: BetterAuthSignOutApi;
}

BetterAuthCredentialMutationValue#

Success value returned by the credential mutations: a status literal ('signed-in' / 'signed-up' / 'signed-out') and the same-origin redirectTo target the framework redirects to after the mutation (SPEC.md §6.5).

ts
interface BetterAuthCredentialMutationValue<Status extends string> {
  redirectTo: string;
  status: Status;
}

BetterAuthCredentialMutationOptions#

Options for the credential mutations (betterAuthSignInEmailMutation, betterAuthSignUpEmailMutation, betterAuthSignOutMutation). csrf wires in CSRF validation (default-on per SPEC.md §6.6), guard runs an authorization/rate-limit guard, defaultRedirectTo sets the post-mutation redirect target, key overrides the mutation key, and registry/transaction integrate with the app's mutation registry and transaction boundary.

ts
interface BetterAuthCredentialMutationOptions<
  Key extends string,
  Request extends BetterAuthRequestLike,
  GuardedRequest extends Request,
> {
  csrf?: CsrfValidationOptions<Request> | false;
  defaultRedirectTo?: string;
  guard?: Guard<Request, GuardedRequest>;
  key?: Key;
  registry?: MutationRegistry;
  transaction?: <Result>(
    request: Request,
    run: (transactionRequest: GuardedRequest) => Promise<Result>,
  ) => Promise<Result>;
}

BetterAuthRoleUser#

Minimal user shape the role guard reads: an optional id and an optional roles list. Apps' own session-user types structurally satisfy this (SPEC.md §6.5).

ts
interface BetterAuthRoleUser {
  id?: string;
  roles?: readonly string[] | null;
}

BetterAuthRoleSession#

Minimal session shape the role guard reads: an optional user.

ts
interface BetterAuthRoleSession {
  user?: BetterAuthRoleUser | null;
}

BetterAuthRoleRequest#

Minimal request shape the role guard reads: an optional session.

ts
interface BetterAuthRoleRequest {
  session?: BetterAuthRoleSession | null;
}

Constants#

betterAuthSignInEmailInput#

Input schema for betterAuthSignInEmailMutationemail, password, and an optional same-origin next redirect target. Exposed because it is the declared input of the sign-in mutation; reuse it when building the matching login form (SPEC.md §6.5).

ts
const betterAuthSignInEmailInput = s.object({
  email: s.string(),
  next: optionalStringSchema,
  password: s.string(),
});

betterAuthSignUpEmailInput#

Input schema for betterAuthSignUpEmailMutationemail, name, password, and an optional same-origin next redirect target (SPEC.md §6.5).

ts
const betterAuthSignUpEmailInput = s.object({
  email: s.string(),
  name: s.string(),
  next: optionalStringSchema,
  password: s.string(),
});

betterAuthSignOutInput#

Input schema for betterAuthSignOutMutation; sign-out takes no fields.

ts
const betterAuthSignOutInput = s.object({});

betterAuthCredentialMutationErrors#

Declared error map for the credential mutations: a single INVALID_CREDENTIALS failure (with an empty payload) the sign-in/sign-up mutations return when a session was not positively established. Surfaced so apps can render the matching error UI (SPEC.md §6.5).

ts
const betterAuthCredentialMutationErrors = {
  INVALID_CREDENTIALS: s.object({}),
};