Better Auth

Learn how to sign users in with Better Auth and connect its session to Jazz.

Better Auth is a self-hosted auth framework. It runs in the same backend as Jazz, so authenticate asks it directly who the request's session cookie belongs to.

Jazz can be Better Auth's database

You don't need a separate PostgreSQL or other database for Better Auth. With the Jazz adapter, Better Auth keeps its users, sessions and accounts in Jazz, next to your app's data: database: jazzAdapter({ db: async () => jazz.db, schema: app }). See Store Better Auth's tables in Jazz, the Next.js, Better Auth and Vercel guide, and the Better Auth chat example. That's different from a separate Better Auth server that issues JWTs your backend only verifies (with fromJWT): there, Better Auth keeps its own database.

Server

jazz.server.ts
import { betterAuth } from "better-auth";
import { createJazz, sqlite } from "jazz-tools/backend";
import { app } from "./jazz.generated";
import permissions from "./jazz.permissions.json" with { type: "json" };
​
export const auth = betterAuth({
// database: your own, or Jazz itself (see "Store Better Auth's tables in Jazz" below)
emailAndPassword: { enabled: true },
});
​
export const jazz = createJazz({
app,
permissions,
store: sqlite({ path: "./data/jazz" }),
// The Better Auth session cookie decides who the user is.
authenticate: async (request) => {
const session = await auth.api.getSession({ headers: request.headers });
if (!session) return null;
return {
userId: session.user.id,
expiresAt: Math.floor(session.session.expiresAt.getTime() / 1000),
};
},
});

Mount Jazz under /jazz next to Better Auth's own handler, which serves /api/auth/* by default. In Next.js:

app/api/auth/[...all]/route.ts
import { toNextJsHandler } from "better-auth/next-js";
import { auth } from "@/jazz.server";
​
export const { GET, POST } = toNextJsHandler(auth);

For the /jazz route and other frameworks, see Your Own Server. Pass anything your policies need, such as the admin plugin's role, as claims.

Act as the signed-in user

In a route handler, act as the signed-in user with jazz.forReqUser(request), which runs the same authenticate:

messages.ts
import { jazz } from "./jazz.server";
import { app } from "./jazz.generated";
​
export async function messages(request: Request) {
const db = await jazz.forReqUser(request);
return Response.json(await db.all(app.messages, { tier: "remote" }));
}

This keeps the signed-in user's policies and authorship without switching your main backend's own identity. For account-owned rows, compare ownership against session.user in permissions; a Better Auth user ID is not a Jazz account UUID. Never accept a raw account ID from a request as authority.

Client

The plain Better Auth client is enough. Import it from your framework's entry: better-auth/react, better-auth/vue, better-auth/svelte, or better-auth/client for plain TypeScript.

src/lib/auth-client.ts
import { createAuthClient } from "better-auth/react"; // or "better-auth/vue", "better-auth/svelte"
​
export const authClient = createAuthClient();

Behind a dev server proxy

When a separate frontend dev server (Vite, say) proxies /api/auth and /jazz to your backend, Better Auth sees requests from the dev server's origin and answers 403 INVALID_ORIGIN. Add that origin to trustedOrigins:

export const auth = betterAuth({
trustedOrigins: ["http://localhost:5173"],
// ...
});

Connecting to Jazz

JazzProvider asks your backend who is signed in, so forms only call Better Auth's sign-up or sign-in and then refresh(): your backend decides who is signed in, and the session follows it. Jazz owns startup, account changes and error recovery, and also checks again on start, on focus and when another tab signs in or out.

App.tsx
import { JazzProvider, useJazzSession } from "jazz-tools/react";
import { authClient } from "./auth-client";
​
function Root() {
return (
<JazzProvider config={{ serverUrl: "/jazz" }} signedOut={<SignIn />}>
<App />
</JazzProvider>
);
}
​
function SignIn() {
const { refresh } = useJazzSession();
async function signIn(email: string, password: string) {
await authClient.signIn.email({ email, password });
await refresh();
}
// ...your form calls signIn
}

For a full working example, including Better Auth's tables stored in Jazz, see the Better Auth chat example.

Note

If your users start as guests (device accounts) and sign up later, call linkDeviceAccount() after Better Auth's sign-up so they keep their data. See Other / Custom.

Store Better Auth's tables in Jazz

The Jazz Better Auth adapter lets Better Auth keep its users, credentials and sessions in the same Jazz app as your own data, so one main backend serves both. For general Better Auth setup (route handlers, client, plugins), see the Better Auth documentation.

Generate the tables

The Better Auth CLI writes Better Auth's tables, and policies for them, into a generated schema-better-auth/schema.ts module. Your schema.ts spreads them next to your own tables, so a single backend context handles both.

Start with shared Better Auth options.

auth-options.ts
export const authOptions = {
baseURL: process.env.BETTER_AUTH_URL!,
secret: process.env.BETTER_AUTH_SECRET!,
emailAndPassword: { enabled: true },
};

Set BETTER_AUTH_URL to your application server's origin and BETTER_AUTH_SECRET to a private Better Auth secret. Keep plugins, additional fields, and model customizations in these shared options so generation and runtime use the same configuration.

Create a separate configuration for generation. It does not import jazz.generated.ts or open a Jazz session, so it works before either the bindings or Jazz exist. The CLI only requests schema generation; the database callback is deliberately unavailable.

auth-generate.ts
import { betterAuth } from "better-auth";
import { jazzAdapter } from "jazz-tools/better-auth-adapter";
import { authOptions } from "./auth-options";
​
export const auth = betterAuth({
...authOptions,
database: jazzAdapter({
db: async () => {
throw new Error("The generation config cannot query the database");
},
schema: {},
}),
});

Generate with the Better Auth CLI:

npx @better-auth/cli generate --config ./auth-generate.ts --output ./schema-better-auth/schema.ts --yes

Pass --output relative to the directory you run it in. Don't combine it with --cwd or an absolute path: the adapter resolves the path relative to the current directory, the CLI writes it relative to --cwd. The CLI rewrites the whole module each time, so don't edit it: keep your own tables, relations and policies in schema.ts. Without --yes, the CLI asks before overwriting the file, after the adapter's notes on what to do next. Review the diff when you regenerate.

A new reference column gets a forward relation named <column>Relation (userIdRelation). Reverse relations aren't generated. Table and column names must be identifiers ([A-Za-z_][A-Za-z0-9_]*), so a modelName or fieldName with a hyphen is refused, with a message saying to rename it.

The generation config passes schema: {} because it only generates tables. The adapter in your running app takes the generated app (see Use Jazz as the database): with {} there, it would find no tables.

The module exports tables (better_auth_account, better_auth_jwks, better_auth_session, better_auth_user and better_auth_verification, plus any your plugins add) and permissions. Spread both into schema.ts. For a chat app, your own messages table sits next to the better_auth_* tables:

schema.ts
import { schema as s } from "jazz-tools";
import { tables as authTables, permissions as authPermissions } from "./schema-better-auth/schema";
​
export const schema = s.defineSchema({
...authTables,
messages: s.table({
author_name: s.string(),
chat_id: s.string(),
text: s.string(),
sent_at: s.timestamp(),
}),
});
​
const { definePermissions } = schema;
​
export const permissions = definePermissions({
// Denies every operation on the better_auth_* tables
...authPermissions,
messages: { read: true },
});

The generated permissions deny every operation on the Better Auth tables, so regular client sessions can't read or write Better Auth rows; the adapter itself uses jazz.db, which has backend authority. definePermissions needs every table listed, so spread authPermissions in next to your own policies rather than leaving the tables out. Never add allow rules for these tables: client sessions have no business reading them.

Then write the app files and bindings:

npx jazz-tools generate

If the Better Auth CLI changed tables a version you already shipped has, jazz-tools generate asks for a migration first: run npx jazz-tools migrations create --name <name>, fill in any TODO it leaves, and run npx jazz-tools generate again. See Migrations.

Use Jazz as the database

Create Jazz in your backend (Main Backend), then pass jazz.db to jazzAdapter(...) as the database in your Better Auth config. Pass the app from jazz.generated.ts as schema, so Better Auth and your own tables share a single Jazz app. authenticate asks the same Better Auth instance who a request's session cookie belongs to.

auth.ts
import { betterAuth } from "better-auth";
import { createJazz, sqlite } from "jazz-tools/backend";
import { jazzAdapter } from "jazz-tools/better-auth-adapter";
import { app } from "./jazz.generated";
import permissions from "./jazz.permissions.json" with { type: "json" };
import { authOptions } from "./auth-options";
​
export const jazz = createJazz({
app,
permissions,
store: sqlite({ path: "./data/jazz" }), // or vercel() / remote(), as for any backend
authenticate: async (request) => {
const session = await auth.api.getSession({ headers: request.headers });
if (!session) return null;
return {
userId: session.user.id,
expiresAt: Math.floor(session.session.expiresAt.getTime() / 1000),
};
},
});
​
export const auth = betterAuth({
...authOptions,
database: jazzAdapter({
db: async () => jazz.db,
schema: app,
}),
});
OptionDescription
dbA function returning Db or Promise<Db>, such as jazz.db.
schemaapp, from jazz.generated.ts.
debugLogsBetter Auth adapter debug logging controls.
usePluralWhether Better Auth model names should use plural table names.
prefixTable name prefix (defaults to "better_auth_").
Leave Better Auth joins disabled

The Jazz adapter does not support Better Auth experimental joins yet, so do not enable experimental.joins.

Compatibility

The adapter is currently aligned with Better Auth 1.7.22, and accepts later 1.7.x patch releases (~1.7.22).

Upgrading from Better Auth 1.7.0–1.7.2 changes the auth schema. Before the new version serves traffic:

  1. Duplicate better_auth_account rows that share a (providerId, accountId) pair can only exist in rare setups, where one OIDC providerId was used with several issuers under Better Auth 1.7.0–1.7.2. The adapter keeps account identity unique on that pair, so writes to such accounts would fail with Unique constraint violated. If you see that error after upgrading, reach out to us rather than deleting rows yourself.
  2. Regenerate schema-better-auth/schema.ts as shown in Generate the tables. The account table no longer has a required issuer column.
  3. Run npx jazz-tools migrations create --name remove-better-auth-issuer. Check that the migration it writes under migrations/ drops the column, better_auth_account: { issuer: m.drop.string({ backwardsDefault: "" }) }, replace any TODO left in it, and run npx jazz-tools generate.
  4. Deploy the backend with that migration in the same release as the Better Auth upgrade. Against the old schema, sign-ups and account links fail because issuer is still required.

The adapter catches the most common mistakes: it throws when it starts if your schema still requires issuer, and on the first account write it logs any (providerId, accountId) pairs shared by more than one row.

See the Better Auth 1.7 upgrade guide for changes outside the adapter.

Plugin/FeatureCompatibility
Email & Password auth✅
Social Provider auth✅
Email OTP✅
Compatibility scope

This section reflects the adapter behavior currently covered by this repo's Better Auth integration and tests. If you add plugins that introduce extra tables or custom schema fields, regenerate the tables and run npx jazz-tools generate again (with a migration if it asks for one).