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.
Server
jazz.server.tsimport { 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.tsimport { 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.tsimport { 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.tsimport { 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.tsximport { 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.
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.tsexport 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.tsimport { 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.tsimport { 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.tsimport { 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 backendauthenticate: 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,}),});
| Option | Description |
|---|---|
db | A function returning Db or Promise<Db>, such as jazz.db. |
schema | app, from jazz.generated.ts. |
debugLogs | Better Auth adapter debug logging controls. |
usePlural | Whether Better Auth model names should use plural table names. |
prefix | Table name prefix (defaults to "better_auth_"). |
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:
- Duplicate
better_auth_accountrows that share a(providerId, accountId)pair can only exist in rare setups, where one OIDCproviderIdwas 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 withUnique constraint violated. If you see that error after upgrading, reach out to us rather than deleting rows yourself. - Regenerate
schema-better-auth/schema.tsas shown in Generate the tables. The account table no longer has a requiredissuercolumn. - Run
npx jazz-tools migrations create --name remove-better-auth-issuer. Check that the migration it writes undermigrations/drops the column,better_auth_account: { issuer: m.drop.string({ backwardsDefault: "" }) }, replace anyTODOleft in it, and runnpx jazz-tools generate. - 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
issueris 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/Feature | Compatibility |
|---|---|
| Email & Password auth | ✅ |
| Social Provider auth | ✅ |
| Email OTP | ✅ |