How Auth Works in Jazz
Learn how your backend decides who a user is, how the browser follows your auth, and what a session is.To authenticate users with Jazz, sign in your users with your auth library as usual. Provide an
authenticate function that reads the user's session and returns their user ID, when that session
expires and any claims, which your permission policies can use. In the browser, JazzProvider asks your backend who is
signed in; after your own sign-in or sign-out, call refresh() on the session.
Using Better Auth? Jazz can be its database too, so you don't need a separate PostgreSQL or other database for it.
Your backend decides
When Jazz runs inside your main backend, auth is one function. Your backend already knows who is signed in, so it tells Jazz:
jazz.server.tsimport { createJazz, sqlite } from "jazz-tools/backend";import { auth } from "./auth"; // your Better Auth instance, which can keep its tables in Jazz tooimport { app } from "./jazz.generated";import permissions from "./jazz.permissions.json" with { type: "json" };export const jazz = createJazz({app,permissions,store: sqlite({ path: "./data/jazz" }),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),claims: { role: session.user.role },};},});
userIdis your user's stable ID: any string your auth library provides. Jazz gives each one an account the first time they sign in.expiresAt(required) is when this answer stops holding, as Unix time in seconds: the expiry of the session the user is signed in with (the one a sign-out ends), or a token'sexp. Not the expiry of a short-lived access token your auth refreshes on its own. Without a valid one, Jazz refuses the sign-in: your backend's log says whatauthenticatereturned, and the browser gets only the codeauthenticate_expires_at_missing, which its session's error explains.claimsare anything your policies should see, such as the user's role or organization, undersession.claims.- Return
nullfor a signed-out request. - Return
acceptDeviceAccounts(request)(fromjazz-tools/backend) to let a signed-out device account sync: that's how guests work. Device accounts are refused otherwise. An app with no sign-in at all passesauthenticate: acceptDeviceAccounts. This gates device-account sync only; linking doesn't depend on it.
Jazz asks authenticate on every sign-in, on every sync connection and in jazz.forReqUser, always
while handling that request, so your framework's request helpers (cookies(), withAuth(),
auth()) work there. Return claims that only change when the user's access does.
Several sign-in methods. If your auth library supports multiple sign-in methods, users can use
any of them, as long as your auth library maps them to a single stable ID for each user. Return
that ID from your authenticate function.
When a session expires
A sync connection lasts until the expiresAt its authenticate answer gave, and at most
sessionTtlSeconds (one hour by default). Shortly before then, a browser on your app's cookie asks
your backend again over an ordinary request, one tab at a time (through
refresh, if you set it). If authenticate still names
the same user with the same claims, the open connection continues to the new expiresAt, without
reconnecting.
Otherwise the client reconnects shortly before expiresAt, and authenticate decides on the new
connection's request. That happens when the renewal request fails (a network error, a 5xx, refresh
throwing), when the user's claims changed, and when the renewal reaches another instance than the
one holding the connection (vercel(), or remote() without a secret). Token-based clients
(React Native, apps passing a token, backend clients) and device-account guests always reconnect at
expiry, with a fresh token. On that reconnect:
- Still the same user: the client carries on. It swaps connections underneath, and your app sees no change: no reconnecting status, no event, and queries and writes continue.
- Their claims changed (say their role): the new connection carries the new claims, so your policies see them from then on.
- No one, or someone else: the connection is refused, and the browser asks your backend who is
signed in. In a tab that is in view, a second answer about two seconds later confirms it, and
Jazz signs the user out (after
onSignedOut). A tab in the background waits until it is in view again. Writes made in between don't sync. At the sign-out, a thin client drops them, and a local-first one keeps them on the device for that user's next sign-in (withclearOnSignOut, it wipes them). Either way, Jazz logs how many there were.
So a sign-out on another device, a ban or a changed role reaches an open connection within
sessionTtlSeconds at the latest. To end a user's open connections at once, call
jazz.revokeUser(userId) from your sign-out handler or your auth provider's session-revoked
webhook. It ends their connections on every backend instance, including one still signing in as
them when you call it (say a tab reconnecting). On Vercel and other serverless hosts, the request
that signs a user out usually runs on a different instance than their sync connections, so
revokeUser records the revocation at the core. The core ends the user's connections wherever
they are served, and refuses any that an instance admits afterwards on an authenticate answer
from before the call. A sign-in after the call works as usual. This needs a core at least as new as
your backend; in front of an older core, revokeUser ends this instance's connections only, and
warns. To sign out the browser the user is in, every tab of it, call refresh() on the client
after your sign-out (see Signing out in every tab). A connection
revokeUser does end asks your backend who is signed in, in a background tab too: the refusal
says the session was revoked, so a "no one" answer there signs the user out as in a tab in view
(confirmed by a second answer two seconds later, after onSignedOut). Until then the link reads
{ state: "offline", reason: "auth", authReason: "revoked" } in db.getSyncStatus(), and writes
made meanwhile stay pending: stop taking edits from there if your app shouldn't accept them. A
connection the server refuses because the user's account identity was retired reads as revoked
too, and signs out the same way. Once the tab is admitted again (your backend still names the
user), the reason is forgotten.
Keep auth middleware off Jazz's routes
authenticate should only read and verify the user's session; never refresh it there. Auth
middleware that refreshes sessions (AuthKit's authkitMiddleware, Clerk's clerkMiddleware,
Auth.js's auth as middleware) must not run on Jazz's routes (/jazz/* by default). When a laptop
wakes, every window of a browser can reach Jazz at about the same moment; with refresh tokens that
work once, all but one of those refreshes fail, and the middleware deletes the session cookie. Pages
keep refreshing the session as usual.
In Next.js, leave Jazz's path out of the middleware's matcher:
middleware.tsexport const config = {// Everything except Next.js internals, static files and Jazz's routes.matcher: ["/((?!_next/static|_next/image|favicon.ico|jazz/).*)"],};
The same matcher works for AuthKit, Clerk and Auth.js middleware. In authenticate, read the
session without refreshing it, and return its expiry as expiresAt.
To refresh the session for Jazz, pass refresh to createJazz: middleware that runs only on the
request a browser makes to ask who is signed in, one tab at a time. Refresh there, call next with
the refreshed cookie, and add your rotated Set-Cookie to its response. See
WorkOS for a complete example.
In the browser
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 SignOutButton() {const { refresh } = useJazzSession();async function signOut() {await authClient.signOut();await refresh();}return <button onClick={() => void signOut()}>Sign out</button>;}
Jazz asks your backend who is signed in at these moments; the identity always comes from
authenticate:
- when the app starts;
- when the page regains focus or becomes visible again;
- when another tab of the same browser changes account (signs in, out, or as someone else);
- when the sync server refuses the connection's sign-in, for example once
expiresAtorsessionTtlSecondshas passed andauthenticateno longer names the user, or afterjazz.revokeUser; - when your app calls
refresh().
A "no one is signed in" answer signs the user out only once a second answer, two seconds later,
agrees, so one failed session refresh in authenticate signs no one out. After refresh() Jazz
follows the first answer. After a refused connection, a tab in the background doesn't sign out on
its own: its cookies may be stale, so it asks again when it is in front. A connection
jazz.revokeUser ended is the exception: the backend ended it on purpose, so a background tab
follows the two answers as a tab in view does. A failed check (a network
error, a timeout, a 5xx) is tried again with backoff. A device remembers the
user your backend signed in (their account, identity and claims, never a credential), so a reload
reopens their account straight away, offline too, and the first answer confirms it: another user
switches in one step, a signed-out answer (confirmed by a second one) signs them out, and changed
claims refresh. Until an answer arrives, the remembered user stays signed in: while your backend is
offline or answers with an error, a reload keeps opening their account on that device. On shared
devices, pass clearOnSignOut: true to createJazzClient: the device then never remembers the
user, so a reload waits for your backend's answer. That wait (the provider shows loading) lasts
at most 5 seconds: a slower backend (cold-starting or hung) opens the session signed-out, the
check keeps running, and the user is signed in when the answer arrives. After your own sign-in or
sign-out, call refresh() from useJazzSession() and Jazz follows your backend's answer.
Without React, call refresh() on the session createJazzClient returns.
If Jazz can't ask your backend (it is offline, or authenticate throws or returns no expiresAt),
refresh() rejects, and the session shows the failure too: it keeps its current user and client
(status stays "ready"), with error set and recovery: "action". retry() asks your backend
again.
- Sign-out. When your backend answers signed out, Jazz closes the account's client. A local-first client's
unsynced writes stay in that account's local storage and sync the next time the same user signs
in. On shared devices, pass
clearOnSignOutto wipe them instead. - Sign-out elsewhere. On another device, or a session that expired or was revoked: when the
connection re-authenticates at its
expiresAt(orjazz.revokeUserends it) andauthenticatereturnsnull, Jazz signs the user out. No client code needed. Other tabs of the same browser follow at once only when the tab that signed out callsrefresh(); see below. - Before a sign-out. Pass
onSignedOuttocreateJazzClientto hear about a confirmed sign-out before Jazz signs the user out. Return"keep"to stay signed in for now (your app refreshes its session itself, or shows its sign-in first); Jazz asks your backend again on the next focus orrefresh(). Return"sign-out", or nothing, to sign out.
Without a framework, call refresh() from your auth library's own listener:
import { createJazzClient } from "jazz-tools/client";const session = await createJazzClient({ serverUrl: "/jazz" });supabase.auth.onAuthStateChange(() => void session.refresh());
Signing out in every tab
refresh() is what makes the browser's other tabs follow: once this tab's session changes account,
it tells the others, and they ask your backend at once. A sign-out that redirects skips it. That
includes AuthKit's signOut(), a Next.js server action that calls redirect(), and Auth.js's
default sign-out. The tab leaves before Jazz hears of it, and unless the page it lands on opens Jazz
(AuthKit's goes through WorkOS's own sign-out page first), nothing tells the other tabs: they follow
only when they're in front again, or when their connection's session ends (expiresAt, or
sessionTtlSeconds, an hour by default).
So sign out in three steps: clear your session without redirecting, call refresh(), then
navigate:
SignOutButton.tsx"use client";import { useRouter } from "next/navigation";import { useJazzSession } from "jazz-tools/react";import { signOutAction } from "./actions"; // ends the session and clears its cookie, no redirect()export function SignOutButton() {const { refresh } = useJazzSession();const router = useRouter();async function signOut() {await signOutAction();await refresh(); // this tab follows, and tells the browser's other tabsrouter.push("/");}return <button onClick={() => void signOut()}>Sign out</button>;}
In React Native
An app has no cookie for your backend, so it passes its own token as bearer, which Jazz sends
as Authorization: Bearer …; your authenticate reads that header. See
Sign in through your backend.
In Node, Deno, Bun or a CLI
A host without cookies passes your app's own token for your backend as bearer, a function that
returns the token or null while no one is signed in. Jazz calls it each time it needs the token
and sends it as Authorization: Bearer … when signing in or linking through your backend, when it
checks who is signed in, and on its sync connections, thin and local-first. Your authenticate
reads that header.
cli.tsimport { createJazzClient } from "jazz-tools/client";import { loadSavedToken } from "./token-store";const session = await createJazzClient({serverUrl: "https://my-app.com/jazz",bearer: () => loadSavedToken(), // your app's session token, or null when signed out});
Outside a browser, the session keeps who is signed in in memory, for as long as the process runs:
a client your backend signs in through bearer asks it again on each start. A device account
needs its key kept somewhere: there, pass createJazzClient a store (an AccountStore from
jazz-tools/client, with read and an atomic update), such as a file. Without one,
initial: "device", createDeviceAccount() and the other device-account operations reject with
DeviceAccountNeedsStoreError.
After your own sign-in or sign-out, call session.refresh() so Jazz asks your backend again.
Sync connections carry the token only to your app's own origin.
bearer is refused in a browser page or worker, where your backend's cookie names the user; leave
it out there. It is also refused on a client with serverUrl: null, which never talks to a
backend. On React Native, pass it in the config of the native createJazzClient or
<JazzProvider config> (see above). Without bearer, refresh() on a host
without cookies fails with an error saying so.
The session
Once signed in, every context has a read-only session. session.user is the account and
session.identity is the exact login acting for it:
const session = db.getAuthState().session;session?.user; // "00000000-0000-4000-8000-000000000001", the accountsession?.identity; // { issuer: "jazz:backend", subject: "alice" }, subject = the userId from authenticate
On the client, the Jazz session names the same user: getSnapshot().user (or user from
useJazzSession()) is { accountId, kind, identity, claims }, or null while no one is signed in.
kind is "device" for a device account and "backend" for a
user your backend signed in; identity.subject is your own user ID.
- Ownership compares
session.user. Linked identities share one account, so this is what "rows this user owns" should use:{ $createdBy: session.user }or{ owner_id: session.user }, also insideexistsrules. - Exact authorship compares
session.identity, issuer and subject included:{ "$createdBy.identity": session.identity }. Jazz stamps$createdByand$updatedBywith the full author record,{ account, identity }, along with edit timestamps. This tells apart writes by the same account made through your auth (jazz:backend), through a device account's key (urn:jazz:local-first), or by your backend on the user's behalf without attribution (urn:jazz:system, see System-authored rows). session.claimsholds the claimsauthenticatereturned. A claim nameduserstays undersession.claims.userand can't shadowsession.user. Claims never decide which account a request belongs to.
session.user is not a profile row, a display name or a subject string. Store a UUID account column
for ownership, or a matching structured column for exact authorship, rather than serializing the
author into a string.
Observe the current session
The Jazz session's user is who is signed in, and it is what your policies see:
user.accountId is session.user, and user.identity and user.claims are session.identity and
session.claims. It is null while no one is signed in.
| Binding | Read the signed-in user |
|---|---|
| React / React Native | const { user } = useJazzSession() |
| Vue | const { snapshot } = useJazzSession(); read snapshot.value.user |
| Solid | const { snapshot } = useJazzSession(); read snapshot().user |
| Svelte | const session = getJazzSession(); read $session.user |
| TypeScript | session.getSnapshot().user; subscribe with session.subscribe(...) |
user.kind tells a device account ("device", a guest) from a user your backend signed in
("backend").
Framework hooks must run inside the Jazz provider. Signed-out readers have no session account, so ownership checks against them fail closed; write an explicit anonymous-access policy when you want that access.
Rows the user owns
If a row always belongs to whoever created it, you don't need a column: compare $createdBy with
session.user in your policy ({ $createdBy: session.user }). When ownership can move to someone
else, such as a reassigned task or a transferred document, store the current owner in its own UUID
column and base your policies on it:
schema.tsimport { schema as s } from "jazz-tools";export const schema = s.defineSchema({todos: s.table({title: s.string(),owner_id: s.uuid(),}),});const { definePermissions, session } = schema;export const permissions = definePermissions({todos: {read: { owner_id: session.user },insert: { owner_id: session.user },},});
Then read and insert with the session's account:
const accountId = db.getAuthState().session?.user;if (accountId) {const todos = await db.all(app.todos.where({ owner_id: accountId }));db.insert(app.todos, { title: "First task", owner_id: accountId });}
A client-side filter is a convenience; the policy is what enforces access. Update and delete stay
denied until you grant them. Assigning owner_id doesn't change who Jazz records as the author. See
Declarative Permissions.
System-authored rows
Writes your main backend makes without acting for a user use the same structure, with a reserved account and issuer:
const systemAuthor = {account: "00000000-0000-0000-0000-000000000000",identity: {issuer: "urn:jazz:system",subject: "00000000-0000-4000-8000-000000000042", // originating node UUID},};
SYSTEM_ACCOUNT_ID and SYSTEM_ISSUER are exported from jazz-tools. Comparing accounts groups all
system writes; comparing the whole structure tells their originating nodes apart. The reserved
account and issuer can't be registered or linked, and they grant no way around your policies.
Acting for a user in your backend
Your main backend has full access by default. To run code as a user instead:
await jazz.forReqUser(request)runsauthenticateon the request and returns a scope with that user's policies and authorship.await jazz.withAttribution(request)keeps backend access but records the request's user as author. Use it only after your own code has made the authorization decision.
Both need the user to have a Jazz account already, from a client sign-in, a guest link or
jazz.createAccountFor(userId). Otherwise they throw NoJazzAccountError (code: "no_account"):
your backend never creates an account on its own. See
Users without an account.
A copied account ID or claim is not authorization: Jazz checks the request or handle itself. See Backend Client for background jobs and other machines.
Guests and linking
Guests are device accounts: accounts whose key lives on the device.
A guest who signs up keeps its account and data: after your sign-up sets its session, the client
calls linkDeviceAccount(). It proves it owns the device account by signing a one-time challenge
with its key; your backend runs authenticate and links the new user to that account. Call it in
your sign-up handler, right after your auth sets the session. The session also links on its own when
it finds a signed-in user with no Jazz account yet; pass linkDeviceAccountOnSignUp: false in the
config of createJazzClient (or <JazzProvider config>) on shared devices.
acceptDeviceAccounts gates device-account sync, not linking. A link is authorised by your
backend's sign-in (authenticate names the user) plus the device key's proof, so it works even
when your app doesn't accept device accounts for sync, for example for a device account made
offline or before you turned guests off.
By default the guest's key stays an identity of the account, so the device can still sign in as the
guest, for example offline. Set guestKeyAfterLink: "revoke" on createJazz to stop the guest key
signing in to a linked account, so a leaked key doesn't give access to a linked account after
linking. Users then need their normal sign-in, which may prevent them from reopening the account
while offline.
To link from your own backend code instead, for example a second identity your auth issued, call:
app/api/sign-up/route.tsawait jazz.linkIdentity({ from: guestId, to: user.id });
From then on, authenticate returning user.id opens the guest's account and all its data. An
identity can belong to only one account, so to must not have signed in to Jazz on its own yet.
Linking keeps the account ID; earlier rows keep their original issuer and subject.
Shared devices
On a computer several people use, such as a family laptop or a library terminal:
- Pass
clearOnSignOut: truetocreateJazzClient(or<JazzProvider config>). The device then never remembers the user, and signing out wipes the account's local storage after waiting up to 5 seconds for pending writes to upload; writes still unsynced then are lost, and the console says how many. A sign-out Jazz notices on its own (your backend answers signed out, in this tab or another) wipes the same way. - Tabs of one account share its local storage, so it's wiped once the last tab open on that account signs out. A tab that signs out while another tab is still signed in (it signed out of Jazz only, offline say) leaves the data to that tab, unsynced writes included. A tab that closes or crashes without signing out leaves the data behind. Another open page wipes it when it becomes visible or its session changes, or the next page load does, once your backend confirms twice that the user is signed out. Nothing polls in the background.
- Guests too. A guest's local storage is wiped once the last tab on it signs out. If its tab closes without signing out, the data stays as long as the device keeps the guest's key (it can be opened again), and is wiped once the key is gone (the guest was linked to a user who signed up).
- A wipe a crash interrupts is finished before that account's data opens again, so a half-deleted store is never read.
- Sign the old user out before you sign the next one in. The wait for pending writes covers only
writes the server still accepts: once your session cookie names the new user, nothing can upload
the old user's writes. So a user switch while offline drops the old user's unsynced writes from
other tabs when sync returns. If that matters, sign out first (your sign-out, then
refresh()), and set the new user's cookie only after that. - Pass
linkDeviceAccountOnSignUp: false, so a guest left on the device by someone else isn't linked to the next person who signs up. See Guests and linking. - Keep personal data out of
userIdand claims. Every reader of a user's rows seesidentity.subjectin$createdByand history (see Metadata), and withoutclearOnSignOutthe device remembers the user's claims. - After your own sign-out, call
refresh()rather than only redirecting, so Jazz follows your backend's signed-out answer straight away.
Lifecycle
<JazzProvider> and createJazzClient run the lifecycle for you. This section explains what happens underneath, and
how to own it yourself.
Switching accounts
When the user changes, Jazz hides the old client, waits for your components to detach, shuts it down gracefully with its writes synced, and only then signs in and opens the new client.
- If the old client can't finish syncing its writes, it stays usable and nothing changes.
- The final sync uploads only what the server still accepts as the old user. Once the session cookie names the new user, the old user's unsynced writes, including other tabs', can't upload any more; see Shared devices.
- If sign-in fails after shutdown, Jazz reopens the previous account when it can.
- If sign-in succeeds but the new client fails to start, the new account stays selected and
retry()retries startup without asking your backend again. - Overlapping account changes reject with a busy error. Sign-out and close win over in-flight work.
Reactive state
useJazzSession() (and getSnapshot()/subscribe() without a framework) reports starting,
ready, signed-out, transitioning, error or closed. A client exists only in ready.
- A failed operation that leaves the client usable (a refused link, a sign-in that failed while the
previous account keeps working) keeps the session
ready, witherrorset andrecovery: "action". Show the error; the app keeps working. status: "error"means there is no usable client: startup failed, or a sign-in or reopen failed.<JazzProvider>shows itserrorview.retry()repeats the failed operation (recovery: "action"), reopens the account (recovery: "session"), or restarts a failed startup.
import { useJazzSession } from "jazz-tools/react";function AccountStatus() {const { status, error, retry } = useJazzSession();return error ? (<button onClick={() => void retry().catch(console.error)}>{error.message}: retry</button>) : (<p>{status === "signed-out" ? "Sign in to continue" : "Loading…"}</p>);}
React Native, Expo, Vue and Solid (useJazzSession()) and Svelte (getJazzSession()) expose the
same state and operations.
Signing out and closing
Signing out stays signed out until a user signs in again, across reloads too: with
initial: "device", Jazz doesn't create a new device account over a sign-out. It doesn't erase
local data or revoke anything at your auth provider; you are still responsible for any clean-up
your auth library requires. A device account's key stays on the device, and
session.reopenDeviceAccount() signs back in as it, with its data (see
Signing out of a device account).
With clearOnSignOut, the key is forgotten and the data wiped.
session.signOut() signs out of Jazz only. While your own auth still has the user signed in (its
sign-out failed offline, say), Jazz signs them back in on its next answer from your backend: sign
out of your auth first, then call refresh().
signOut() waits for the account's writes to upload. When they can't yet (offline), it rejects and
the tab stays signed in, so you can call it again. The device already counts the account as signed
out: a reload opens no one, and the next sign-in gets its own account. The account's key and
unsynced writes stay on the device, and upload when it signs in again.
Closing a client keeps local data on the device and works offline, but doesn't guarantee that sync completes. Changing accounts does.
Resetting browser storage
await db.deleteClientStorage() clears the active browser namespace and keeps the client usable.
It permanently deletes unsynced writes and local-only data. Data comes back only if it already
reached your backend and the same account can still read it. It keeps device account keys and doesn't
sign anyone out. The browser console helper does the
same. If another tab holds the account's storage under another sign-in (a guest who just signed up
in this tab), or with another build's schema (a tab of the app's previous deploy), it waits for
that tab to follow, reload or close; after 30 seconds it fails with a
StoreHeldByAnotherTabError, and you can call it again once that tab is gone.
Owning the session yourself
The session createJazzClient returns also takes explicit commands:
import { createJazzClient } from "jazz-tools/client";const session = await createJazzClient({ serverUrl: "/jazz", initial: "device" });session.db.insert(app.todos, { title: "Written as a guest", done: false });await session.refresh(); // follow the user your backend's authenticate names nowawait session.linkDeviceAccount(); // after a sign-up: the new user keeps this guest's dataawait session.signOut();await session.close();
By default, the session starts signed out. Pass initial: "device" to reopen the saved device
account or create a new one. session.db is the signed-in user's Db; it throws while there is none,
and the session replaces it when someone signs in or out, so read session.db again after those
rather than keeping it. In React, pass the session to <JazzProvider session={session}>; the
provider then leaves closing it to you.