---
title: Use Better Auth
description: "Store Better Auth’s users, sessions, and accounts in your Arbor database."
seo:
  description: "Use Better Auth with Arbor on D1, Postgres, SQLite, and MySQL: arborAdapter from @forestfuture/arbor/better-auth, your own Models, npx auth generate for its tables, and its keys."
---

## 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:

```sh
npm install better-auth
```

Then pass `arborAdapter()` to `betterAuth` as its database:

```ts
// 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:

```ts
import { withDatabase } from "@forestfuture/arbor";
import { connect } from "@forestfuture/arbor/d1";
import { auth } from "./auth";

// src/worker.ts: Better Auth answers its own routes, its queries going through the request's database.
export const worker = {
  fetch(request, env) {
    return withDatabase(connect(env.DB), () => auth.handler(request));
  },
} satisfies ExportedHandler<Env>;
```

Set `BETTER_AUTH_SECRET` and `BETTER_AUTH_URL` as Better Auth’s installation guide says.

:::note
`withDatabase` needs Node.js compatibility, which is on by default for compatibility dates from 2026-08-04. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]`.
:::

To send every query through one database without `withDatabase`, pass it as `database`:

```ts
import { arborAdapter } from "@forestfuture/arbor/better-auth";
import { connect } from "@forestfuture/arbor/d1";
import { betterAuth } from "better-auth";

// src/worker.ts: every query through one database, with no withDatabase around it.
export const direct = {
  fetch(request, env) {
    const perRequest = betterAuth({
      database: arborAdapter({ database: connect(env.DB) }),
      emailAndPassword: { enabled: true },
    });
    return perRequest.handler(request);
  },
} satisfies 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:

```ts auth.ts
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 },
});
```

```ts user.ts
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 as `users` fails at once.
- **Your Model’s table and columns hold the data.** Better Auth’s `fields` renames name its attributes, so `fields: { email: "emailAddress" }` reads and writes `User.emailAddress`. Its `modelName` doesn’t move a mapped table.
- **Bulk writes skip callbacks.** Better Auth spends tokens and counts requests with `updateMany` and `deleteMany`, 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](#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](#making-keys) |

- **A Model that doesn’t fit** throws one `InvalidModel` naming 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:

```ts
import { arborAdapter } from "@forestfuture/arbor/better-auth";
import { betterAuth } from "better-auth";

// src/auth.ts: the users in a table named members, and their email in email_address.
export const renamed = betterAuth({
  database: arborAdapter(),
  user: { modelName: "members", fields: { email: "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 your `generateId`. Otherwise it extends `Model`, and needs `database` or `withDatabase`.
- **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:

```sql D1
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);
```

```sql Postgres
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.sql` in 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 with `arbor migrate` first.
- **`arbor migrate` adds 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 are `COLLATE utf8mb4_bin` too, so a token matches only itself. A string with no index is `TEXT`, so a long OAuth token fits, and an indexed one is `VARCHAR(255)`.

## Adding a plugin later

Add the plugin to Better Auth’s options, then generate and apply the migration again:

```sh
npx auth generate
npx arbor migrate
```

- **The new migration holds** the plugin’s tables and the columns it adds to yours. A `twoFactor` table is `two_factors`, and its `backupCodes` field is `backup_codes`.
- **A required column added to a table you have** gets its `defaultValue` in 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](#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`:

```text
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 `defaultValue`** can be null, since your existing rows have no value for it. Fill them in, then make it `NOT NULL` in 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](#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:

```ts
// 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 `generateId` when you map at least one Model and every one extends that class. Otherwise its keys are UUIDs.
- **Better Auth’s own `advanced.database.generateId`** wins when it’s `"uuid"` or a function. With `false`, Better Auth gives no key, and the Model’s `generateId` makes one.
- **Keys Better Auth makes itself,** such as a verification’s, are kept as they are.
- **Your Model’s key is a `string` attribute named `id`.** Better Auth’s own keys aren’t UUIDs. Under `generateId: "uuid"` it may be a `uuid`. 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:

```ts
// 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:

```json
{ "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’s `APIError` from the callback.
- **A database constraint,** such as a duplicate key, reaches Better Auth as it is, so it can recognize a duplicate it expects.

:::warning[Leave uniqueness to the database here]
Better Auth makes a verification’s key and a device authorization’s codes knowing that a duplicate insert fails, and reads the database’s refusal. A `uniqueness` validation on one of them turns that refusal into a 422 Better Auth doesn’t recognize.
:::

## 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 `resolveUser` and `guardProviderMutation` don’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:

```ts
// 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:

```ts
// 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 `fetch` from your server.** Use one that passes it a `Request`, since Node doesn’t serve a default export.
- **A Worker defines `auth` once.** Your module’s `auth` serves every request, and each request’s queries go through the database its `withDatabase` names.
- **A Worker’s bundle leaves out Arbor’s command.** The adapter loads it only when `npx auth generate` runs.
