Use Better Auth
Store Better Auth’s users, sessions, and accounts in your Arbor database.
At a glance
| To | Write |
|---|---|
| store Better Auth’s data through Arbor | betterAuth({ database: arborAdapter() }) |
store Better Auth’s users through User |
arborAdapter({ models: { user: User } }) |
| answer Better Auth’s routes in a Worker | withDatabase(connect(env.DB), () => auth.handler(request)) |
| send every query through one database | arborAdapter({ database: connect(env.DB) }) |
| rename a table or a column without a Model | Better Auth’s modelName and fields, under Arbor’s names |
| make Better Auth’s tables | npx auth generate, then arbor migrate |
| tell a person why sign-up failed | a validation on your Model, answered with a 422 |
| batch a list’s one-to-one joins | advanced: { database: { joins: true } } |
| answer Better Auth’s routes on Bun | withDatabase(connect(path), () => auth.handler(request)) |
arborAdapter takes:
| Option | Type | Default |
|---|---|---|
models |
your Models, by Better Auth’s model key | a Model the adapter builds for each table |
database |
Database |
each query’s own database: the request’s withDatabase |
Setting up
Install Better Auth beside Arbor:
npm install better-auth
Then pass arborAdapter() to betterAuth as its database:
// src/auth.ts: Better Auth, storing its users, sessions and accounts through Arbor.
import { betterAuth } from "better-auth";
import { arborAdapter } from "@forestfuture/arbor/better-auth";
export const auth = betterAuth({
database: arborAdapter(),
emailAndPassword: { enabled: true },
});
Answer Better Auth’s routes inside withDatabase, so its queries go through the request’s database:
import { function withDatabase<R>(databases: AnyDatabase | readonly AnyDatabase[], fn: () => R | Promise<R>): Promise<R>Runs `fn` with `databases` as the request's own: queries started from a Model inside it (and
everything it awaits) use the one on that Model's binding, with its Session and `onQuery`.
Usually called once per request, in middleware. Nested calls add to the outer ones.
Each call is a scope of its own, even with a Database another request shares. An adapter may
hold a connection for the scope (the PostgreSQL adapter does, from a connection string). A nested call with
the same Database shares the outer call's scope while that call is running. When `fn` settles,
the scope ends, and the adapter lets its connection go once the queries still running on it
finish. Work that outlives the scope, such as a `waitUntil` save, gets a connection of its own.withDatabase } from "@forestfuture/arbor";
import { function connect(binding: D1Database, options?: ConnectOptions): Databaseconnect } from "@forestfuture/arbor/d1";
import { const auth: Auth<{
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
emailAndPassword: {
enabled: true;
};
}>
auth } from "./auth";
// src/worker.ts: Better Auth answers its own routes, its queries going through the request's database.
export const const worker: {
fetch(request: Request<unknown, IncomingRequestCfProperties<unknown>>, env: Env): Promise<Response>;
}
worker = {
ExportedHandler<Env, unknown, unknown, unknown>.fetch?: ExportedHandlerFetchHandler<Env, unknown, unknown> | undefinedfetch(request: Request<unknown, IncomingRequestCfProperties<unknown>>request, env: Envenv) {
return withDatabase<Response>(databases: AnyDatabase | readonly AnyDatabase[], fn: () => Response | Promise<Response>): Promise<Response>Runs `fn` with `databases` as the request's own: queries started from a Model inside it (and
everything it awaits) use the one on that Model's binding, with its Session and `onQuery`.
Usually called once per request, in middleware. Nested calls add to the outer ones.
Each call is a scope of its own, even with a Database another request shares. An adapter may
hold a connection for the scope (the PostgreSQL adapter does, from a connection string). A nested call with
the same Database shares the outer call's scope while that call is running. When `fn` settles,
the scope ends, and the adapter lets its connection go once the queries still running on it
finish. Work that outlives the scope, such as a `waitUntil` save, gets a connection of its own.withDatabase(function connect(binding: D1Database, options?: ConnectOptions): Databaseconnect(env: Envenv.Env.DB: D1DatabaseDB), () => const auth: Auth<{
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
emailAndPassword: {
enabled: true;
};
}>
auth.handler: (request: Request) => Promise<Response>handler(request: Request<unknown, IncomingRequestCfProperties<unknown>>request));
},
} satisfies interface ExportedHandler<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown, Props = unknown>ExportedHandler<Env>;Set BETTER_AUTH_SECRET and BETTER_AUTH_URL as Better Auth’s installation guide says.
To send every query through one database without withDatabase, pass it as database:
import { function arborAdapter({ models, database }?: ArborAdapterOptions): (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>Better Auth's database adapter on Arbor: `betterAuth({ database: arborAdapter() })`. Better
Auth's flows run without a transaction, as Arbor has no interactive ones, and each key is made
by the `static generateId` of the table's Model, unless Better Auth's own `generateId` is set.arborAdapter } from "@forestfuture/arbor/better-auth";
import { function connect(binding: D1Database, options?: ConnectOptions): Databaseconnect } from "@forestfuture/arbor/d1";
import { const betterAuth: <Options extends BetterAuthOptions>(options: Options & {}) => Auth<Options>Better Auth initializer for full mode (with Kysely)betterAuth } from "better-auth";
// src/worker.ts: every query through one database, with no withDatabase around it.
export const const direct: {
fetch(request: Request<unknown, IncomingRequestCfProperties<unknown>>, env: Env): Promise<Response>;
}
direct = {
ExportedHandler<Env, unknown, unknown, unknown>.fetch?: ExportedHandlerFetchHandler<Env, unknown, unknown> | undefinedfetch(request: Request<unknown, IncomingRequestCfProperties<unknown>>request, env: Envenv) {
const const perRequest: Auth<{
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
emailAndPassword: {
enabled: true;
};
}>
perRequest = betterAuth<{
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
emailAndPassword: {
enabled: true;
};
}>(options: {
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
emailAndPassword: {
enabled: true;
};
}): Auth<{
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
emailAndPassword: {
enabled: true;
};
}>
Better Auth initializer for full mode (with Kysely)betterAuth({
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>database: function arborAdapter({ models, database }?: ArborAdapterOptions): (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>Better Auth's database adapter on Arbor: `betterAuth({ database: arborAdapter() })`. Better
Auth's flows run without a transaction, as Arbor has no interactive ones, and each key is made
by the `static generateId` of the table's Model, unless Better Auth's own `generateId` is set.arborAdapter({ ArborAdapterOptions.database?: AnyDatabase | undefinedThe Database every query goes through. Without it, each query finds its database as a
Model's own query does: the request's `withDatabase`, or else the Model's binding.database: function connect(binding: D1Database, options?: ConnectOptions): Databaseconnect(env: Envenv.Env.DB: D1DatabaseDB) }),
emailAndPassword: {
enabled: true;
}
emailAndPassword: { enabled: trueenabled: true },
});
return const perRequest: Auth<{
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
emailAndPassword: {
enabled: true;
};
}>
perRequest.handler: (request: Request) => Promise<Response>handler(request: Request<unknown, IncomingRequestCfProperties<unknown>>request);
},
} satisfies interface ExportedHandler<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown, Props = unknown>ExportedHandler<Env>;Using your own Models
Pass your Models to arborAdapter by Better Auth’s model key, and Better Auth’s writes go through them:
import { arborAdapter } from "@forestfuture/arbor/better-auth";
import { betterAuth } from "better-auth";
import { User } from "./models/user";
// src/auth.ts: Better Auth's users through your User Model, and its other tables through Models the adapter builds.
export const mapped = betterAuth({
database: arborAdapter({ models: { user: User } }),
emailAndPassword: { enabled: true },
});import { ApplicationRecord } from "./application-record";
export class User extends ApplicationRecord {}- Sign-up runs your Model. Its validations, normalizations, and callbacks run, and its default scope keeps a user it leaves out from signing in.
- Map only the tables you need. A plugin’s table goes in the same map, under its key (
twoFactor: TwoFactor). A key Better Auth doesn’t have throws and lists the keys it has, so a typo such asusersfails at once. - Your Model’s table and columns hold the data. Better Auth’s
fieldsrenames name its attributes, sofields: { email: "emailAddress" }reads and writesUser.emailAddress. ItsmodelNamedoesn’t move a mapped table. - Bulk writes skip callbacks. Better Auth spends tokens and counts requests with
updateManyanddeleteMany, which run as one statement each.
Checking your Models
Each Model in models is checked when it’s first used. It needs a key named id of a type from Making keys, and an attribute of one of these types for each of Better Auth’s fields:
| Better Auth’s type | Your attribute’s type |
|---|---|
string, one of a fixed list of strings |
string |
number |
integer, real, or decimal |
boolean |
boolean |
date |
datetime |
json, string[], number[] |
json |
| a reference to a table’s key | the key’s type, as in Making keys |
- A Model that doesn’t fit throws one
InvalidModelnaming its table and every misfit:User can't serve Better Auth's user table: emailVerified is string, not boolean. - A Model that fits isn’t checked again.
Serving tables without a Model
Each table you leave out of models is served by a Model the adapter builds from Better Auth’s schema, named by Arbor’s conventions:
| Better Auth’s | Is stored in |
|---|---|
model user, plugin model twoFactor |
the table users, two_factors |
field emailVerified |
the column email_verified |
modelName: "members" |
the table members |
fields: { email: "emailAddress" } |
the column email_address |
a field named like a record’s method (save) |
the column of its name (save) |
The renames in Better Auth’s options are names, not columns. Arbor writes them as it writes any attribute:
import { function arborAdapter({ models, database }?: ArborAdapterOptions): (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>Better Auth's database adapter on Arbor: `betterAuth({ database: arborAdapter() })`. Better
Auth's flows run without a transaction, as Arbor has no interactive ones, and each key is made
by the `static generateId` of the table's Model, unless Better Auth's own `generateId` is set.arborAdapter } from "@forestfuture/arbor/better-auth";
import { const betterAuth: <Options extends BetterAuthOptions>(options: Options & {}) => Auth<Options>Better Auth initializer for full mode (with Kysely)betterAuth } from "better-auth";
// src/auth.ts: the users in a table named members, and their email in email_address.
export const const renamed: Auth<{
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
user: {
modelName: "members";
fields: {
email: string;
};
};
}>
renamed = betterAuth<{
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
user: {
modelName: "members";
fields: {
email: string;
};
};
}>(options: {
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
user: {
modelName: "members";
fields: {
email: string;
};
};
}): Auth<{
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
user: {
modelName: "members";
fields: {
email: string;
};
};
}>
Better Auth initializer for full mode (with Kysely)betterAuth({
database: (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>database: function arborAdapter({ models, database }?: ArborAdapterOptions): (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>Better Auth's database adapter on Arbor: `betterAuth({ database: arborAdapter() })`. Better
Auth's flows run without a transaction, as Arbor has no interactive ones, and each key is made
by the `static generateId` of the table's Model, unless Better Auth's own `generateId` is set.arborAdapter(),
user: {
modelName: "members";
fields: {
email: string;
};
}
user: { modelName: "members"modelName: "members", fields: {
email: string;
}
fields: { email: stringemail: "emailAddress" } },
});- It’s built on your base class when you map at least one Model and every one extends the class holding your generated schema, such as
ApplicationRecord. Then it uses your database, your shared callbacks, and yourgenerateId. Otherwise it extendsModel, and needsdatabaseorwithDatabase. - It has no validations or callbacks of its own. Each value is stored as Arbor stores an attribute’s.
- Changing Better Auth’s options changes the names it uses, once Better Auth starts again.
Generating the migration
Run npx auth generate to write Better Auth’s tables to a migration, then apply it with arbor migrate. For email and password sign-in, it writes this:
CREATE TABLE users (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
email TEXT NOT NULL,
email_verified BOOLEAN NOT NULL,
image TEXT,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
CREATE UNIQUE INDEX index_users_on_email ON users (email);
CREATE TABLE sessions (
id TEXT PRIMARY KEY NOT NULL,
expires_at DATETIME NOT NULL,
token TEXT NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
ip_address TEXT,
user_agent TEXT,
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE
);
CREATE UNIQUE INDEX index_sessions_on_token ON sessions (token);
CREATE INDEX index_sessions_on_user_id ON sessions (user_id);
CREATE TABLE accounts (
id TEXT PRIMARY KEY NOT NULL,
account_id TEXT NOT NULL,
provider_id TEXT NOT NULL,
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
access_token TEXT,
refresh_token TEXT,
id_token TEXT,
access_token_expires_at DATETIME,
refresh_token_expires_at DATETIME,
scope TEXT,
password TEXT,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
CREATE INDEX index_accounts_on_user_id ON accounts (user_id);
CREATE TABLE verifications (
id TEXT PRIMARY KEY NOT NULL,
identifier TEXT NOT NULL,
value TEXT NOT NULL,
expires_at DATETIME NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
CREATE INDEX index_verifications_on_identifier ON verifications (identifier);CREATE TABLE users (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL,
email_verified BOOLEAN NOT NULL,
image TEXT,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
CREATE UNIQUE INDEX index_users_on_email ON users (email);
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
expires_at TIMESTAMPTZ NOT NULL,
token TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
ip_address TEXT,
user_agent TEXT,
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE
);
CREATE UNIQUE INDEX index_sessions_on_token ON sessions (token);
CREATE INDEX index_sessions_on_user_id ON sessions (user_id);
CREATE TABLE accounts (
id TEXT PRIMARY KEY,
account_id TEXT NOT NULL,
provider_id TEXT NOT NULL,
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
access_token TEXT,
refresh_token TEXT,
id_token TEXT,
access_token_expires_at TIMESTAMPTZ,
refresh_token_expires_at TIMESTAMPTZ,
scope TEXT,
password TEXT,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX index_accounts_on_user_id ON accounts (user_id);
CREATE TABLE verifications (
id TEXT PRIMARY KEY,
identifier TEXT NOT NULL,
value TEXT NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX index_verifications_on_identifier ON verifications (identifier);- It writes only what your database lacks. Missing tables, columns, and indexes go in a new
<timestamp>_better_auth.sqlin your migrations folder. Nothing there is dropped or changed, and with nothing missing, nothing is written. - It compares with your local database. That’s the database your base class’s schema names, or else the first in
arbor.jsonc. Apply your own migrations to it witharbor migratefirst. arbor migrateadds the tables to your generated schema after it applies the migration.- On MySQL and MariaDB, a key is
VARCHAR(64) COLLATE utf8mb4_bin, and so is each column that references one. Better Auth’s other strings areCOLLATE utf8mb4_bintoo, so a token matches only itself. A string with no index isTEXT, so a long OAuth token fits, and an indexed one isVARCHAR(255).
Adding a plugin later
Add the plugin to Better Auth’s options, then generate and apply the migration again:
npx auth generate
npx arbor migrate
- The new migration holds the plugin’s tables and the columns it adds to yours. A
twoFactortable istwo_factors, and itsbackupCodesfield isbackup_codes. - A required column added to a table you have gets its
defaultValuein your existing rows, when that’s a string, number, or boolean (NOT NULL DEFAULT false). - Anything it can’t do as Better Auth asks gets a note, as Reading the notes shows.
Reading the notes
npx auth generate prints a note for each column it couldn’t make as Better Auth asks, before it tells you to run arbor migrate:
Note: users.nickname can be null, since rows already in users have no value for it, though Better Auth requires one
Note: users.age is string, where Better Auth needs integer, real or decimal; change it in a migration of your own
Run `arbor migrate`
- A required column without a
defaultValuecan be null, since your existing rows have no value for it. Fill them in, then make itNOT NULLin a migration of your own. - A column whose type doesn’t fit is left as it is. Change its type in a migration of your own.
- A table’s key is checked too. Its type must hold Better Auth’s IDs, as Making keys says.
Making keys
Each key is made by the generateId of its table’s Model, a UUID by default. To make Better Auth’s keys with your own function, override it on your base class:
// src/models/application-record.ts
import { Model } from "@forestfuture/arbor";
import { uuidv7 } from "uuidv7";
import { schema } from "../db/schema";
export abstract class ApplicationRecord extends Model {
static override schema = schema;
static override generateId = () => uuidv7();
}
- A table without a Model uses your base class’s
generateIdwhen you map at least one Model and every one extends that class. Otherwise its keys are UUIDs. - Better Auth’s own
advanced.database.generateIdwins when it’s"uuid"or a function. Withfalse, Better Auth gives no key, and the Model’sgenerateIdmakes one. - Keys Better Auth makes itself, such as a verification’s, are kept as they are.
- Your Model’s key is a
stringattribute namedid. Better Auth’s own keys aren’t UUIDs. UndergenerateId: "uuid"it may be auuid. Under"serial"it’s an integer the database counts, and so is each column that references one.
Handling refused writes
A validation your Model fails reaches the person as a 422 with its messages:
// src/models/user.ts
import { ApplicationRecord } from "./application-record";
export class User extends ApplicationRecord {
static {
this.validates("name", { length: { minimum: 3 } });
}
}
Signing up as “Al” is answered with this body:
{ "code": "VALIDATION_ERROR", "message": "Name is too short (minimum is 3 characters)" }
- A callback’s
abort()reaches Better Auth as it is. Better Auth logs it, and answers sign-up with “Failed to create user” and other routes with a 500. To tell the person why, add a validation, or throw Better Auth’sAPIErrorfrom the callback. - A database constraint, such as a duplicate key, reaches Better Auth as it is, so it can recognize a duplicate it expects.
Running without transactions
Better Auth runs each flow’s writes one by one, since Arbor has no interactive transactions. A flow that fails partway keeps the writes before the failure:
| Flow | Writes, in order | Left behind by a failure |
|---|---|---|
| Sign-up with email and password | the user, its account, its session | a user who can’t sign in |
| Sign-in with a new social account | the user, its account | a user with no account |
| Linking a social account | the account, then the user’s verified email | a linked account, the email unverified |
| Resetting a password | spending the reset token, removing the user’s sessions (with revokeSessionsOnPasswordReset), then the password |
a spent token, the old password kept; ask for another reset |
| Deleting a user | its sessions, its accounts, then the user | a user with no sessions or accounts |
To recover from a half-finished sign-up, delete the user. Its sessions and accounts go with it through ON DELETE CASCADE, and the person can sign up again. A failed write reaches Better Auth unchanged, and it answers with its own error.
- Hooks run when the flow ends, even when it fails. A hook Better Auth queues for after a transaction runs once the flow’s writes are done. When the flow fails partway, its hooks still run, since the writes before the failure were kept, and an error in one is logged.
- Some features need a transaction. SCIM and the SSO plugin’s
resolveUserandguardProviderMutationdon’t work, as Better Auth reports when you use them.
Joining tables
Turn on Better Auth’s advanced.database.joins, and a list that joins one row to each of its rows takes one query per joined table:
// src/auth.ts
import { betterAuth } from "better-auth";
import { arborAdapter } from "@forestfuture/arbor/better-auth";
export const auth = betterAuth({
database: arborAdapter(),
advanced: { database: { joins: true } },
});
- A list with a one-to-one join is two queries. Listing an organization’s members with their users reads the members, then their users in one query.
- A one-row read costs the same either way. A session with its user is two queries, with joins on or off.
- Better Auth reads a one-to-many join itself. A user’s accounts take one query for each user on a list, as they do with joins off.
- Your joined Model’s default scope applies. A row it hides joins as
null.
Running on Workers and Bun
On Bun, answer Better Auth’s routes inside withDatabase on your SQLite file, as a Worker does on D1:
// src/server.ts: a Bun server answering Better Auth's routes, its queries going through your SQLite file.
import { withDatabase } from "@forestfuture/arbor";
import { connect } from "@forestfuture/arbor/sqlite";
import { auth } from "./auth";
const db = connect("storage/development.sqlite3");
export default {
fetch(request: Request): Promise<Response> {
return withDatabase(db, () => auth.handler(request));
},
};
- Bun serves the file’s default export. Run
bun src/server.ts. - On Node, call this
fetchfrom your server. Use one that passes it aRequest, since Node doesn’t serve a default export. - A Worker defines
authonce. Your module’sauthserves every request, and each request’s queries go through the database itswithDatabasenames. - A Worker’s bundle leaves out Arbor’s command. The adapter loads it only when
npx auth generateruns.