Backend Client
Learn how to connect other trusted machines to Jazz through your main backend, for machine-to-machine access.Your main backend is the one that runs createJazz: browsers and apps sync
through it, and its authenticate decides who each user is. A backend client is any other
trusted machine that reads and writes the same data, such as a CI job, a worker on another cloud,
a script or a partner's service. It connects to your main backend's /jazz like a browser does,
but proves who it is with its own machine-to-machine credential, not a user's session.
A backend client is one of two kinds:
- Trusted. It acts as the system, with your main backend's own authority: your permissions are not checked, and its writes carry the system identity. It can also act for any user. Use it for system work such as imports, migrations and scheduled jobs.
- Scoped. It acts as one user, with that user's permissions, exactly as if
authenticatehad named the user. Use it for an agent or service that should only touch one account's data.
Trust the machine in your main backend
Most platforms give their workloads an OIDC token: GitHub Actions, Vercel, Google Cloud, Azure and
Kubernetes all do. List each machine you trust in backendClients, naming it by the token's issuer,
audience and the claims only that machine has:
jazz.server.tsimport { createJazz, sqlite, trustWorkload } from "jazz-tools/backend";import { 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) => /* your users' sessions */ null,backendClients: [// The nightly import job in this repo's production environment: a trusted machine.trustWorkload({issuer: "https://token.actions.githubusercontent.com",audience: "jazz:my-app",claims: { sub: "repo:acme/my-app:environment:production" },as: "backend",}),// A support agent that acts as its own user.trustWorkload({issuer: "https://token.actions.githubusercontent.com",audience: "jazz:my-app",claims: { sub: "repo:acme/support-agent:environment:production" },as: () => ({ userId: "support-agent", claims: { role: "agent" } }),}),],});
issueris where Jazz finds the token's signing keys, through its OpenID discovery document.audiencemust match the token'saud, so tokens minted for other services are refused.claimsmust all match exactly. Name the workload down to its environment: every workload of the same issuer gets tokens signed by the same keys, soclaimscan't be empty.asdecides the kind:"backend"for a trusted machine, or a function from the token's claims to a user ({ userId, claims? }, ornullto refuse) for a scoped one.
A token from a listed issuer that fails any check is refused. It never reaches authenticate.
Connect from the machine
On the machine, open a Jazz session against your main backend and pass a function that returns a fresh token. Jazz calls it for every request and socket, so short-lived tokens just work:
import-job.tsimport { createJazzClient } from "jazz-tools/backend";import { app } from "./jazz.generated";import permissions from "./jazz.permissions.json" with { type: "json" };const session = await createJazzClient({app,permissions,serverUrl: "https://my-app.com/jazz",driver: { type: "memory" },credential: githubOidcToken,});await session.db.insert(app.imports, { source: "nightly" }).wait({ tier: "global" });await session.close(); // uploads queued writes first, for up to 10 seconds// GitHub Actions hands out OIDC tokens to jobs with `permissions: id-token: write`.async function githubOidcToken() {const url = `${process.env.ACTIONS_ID_TOKEN_REQUEST_URL}&audience=jazz:my-app`;const response = await fetch(url, {headers: {Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}`,},});return (await response.json()).value as string;}
Depend on the jazz-app-support crate. Write your app's schema and permissions in schema.ts
beside Cargo.toml (the same schema and permissions as your TypeScript main backend), and run
npx jazz-tools generate: it writes jazz.app.json, jazz.permissions.json and
src/jazz_app.rs, the typed bindings. The crate needs no package.json:
Cargo.toml[dependencies]jazz-app-support = "=2.0.0-alpha.66"serde_json = "1"tokio = { version = "1", features = ["full"] }
Run it with npx: the standalone jazz-tools binary refuses to write beside a schema.ts,
though its generate --check still works. Commit schema.ts and the generated files, and
declare the bindings with mod jazz_app;. The Reading
and Writing pages have a Rust tab for each example.
Config::credential(…) takes a function that returns a fresh token, like TS's credential. Your
main backend's backendClients decide whether it's a trusted or a scoped client:
src/main.rs// `jazz_app` is the generated bindings; they re-export jazz-app-support.use jazz_app::{AppFiles, AppId, CLOSE_TIMEOUT, Config, Jazz, Storage, TokenReason, todos};// The main backend trusts this workload in `backendClients`, with// `trustWorkload({ issuer, audience, claims, as })`.let app_id = std::env::var("JAZZ_APP_ID").unwrap_or_default(); // the main backend's `jazz.appId`let config = Config::new(AppId::from_string(&app_id).map_err(|_| jazz_app::Error::Config("JAZZ_APP_ID".into()))?,).server("https://app.example/jazz") // the main backend's Jazz endpoint.storage(Storage::Memory).credential(|_reason: TokenReason| async move {// The workload's OIDC token, read fresh each time it is asked for.std::fs::read_to_string("/var/run/secrets/jazz/token").map(|token| Some(token.trim().to_owned())).map_err(|e| jazz_app::Error::Config(format!("reading the workload token: {e}")))});// A backend client opens with the app's permissions too, as TypeScript's// `createJazzClient` does: the generated bindings embed only the schema.let files = AppFiles::new(jazz_app::APP, None)// your app's jazz.permissions.json.with_permissions(include_bytes!("../../todo-server-rs/jazz.permissions.json").as_slice());let jazz = Jazz::open(files, config).await?;let open = jazz.all(todos::query().filter(todos::done().eq(false))).await?;println!("{} open todos", open.len());// Waits up to 10 seconds for queued writes to reach the main backend.jazz.close(CLOSE_TIMEOUT).await?;
A backend client needs your app's jazz.permissions.json, as TypeScript's createJazzClient
takes permissions: it checks the users it acts for by them. The generated jazz_app::open
embeds only the schema, so open with
Jazz::open(AppFiles::new(jazz_app::APP, None).with_permissions(…), config).
If your main backend can't upgrade sockets, the client falls back to its HTTP stream, as TypeScript clients do.
src/main.rsuse jazz_app::BackendClientKind;// `job` is opened with `Config::credential`, as above. The main backend// decides what the credential is trusted as.match job.backend_client() {// `as: "backend"`: it syncs as the system, and may act for any user.Some(BackendClientKind::Trusted) => println!("a trusted machine"),// `as: (claims) => ({ userId })`: it acts as that one user.Some(BackendClientKind::Scoped) => println!("a scoped machine"),None => println!("not a backend client"),}
job.close(timeout) first waits for the writes the client holds to reach the backend, for up to
the timeout, then stops it. With Storage::Memory, writes still queued are lost and close
returns Error::Unsynced { pending }; Duration::ZERO doesn't wait for them. Either way, calls
still waiting on the server when it stops fail with Error::Stopped. With Storage::Dir, give
each worker a directory of its own: one client at a time has a store open:
src/main.rsuse jazz_app::CLOSE_TIMEOUT;// Waits up to 10 seconds for queued writes to reach the server, then// stops the client. With `Storage::Memory`, writes still queued are lost.match job.close(CLOSE_TIMEOUT).await {Err(Error::Unsynced { pending }) => eprintln!("{pending} writes were lost"),closed => closed?,}
jazz.Credential(provider) takes a function that returns a fresh token, like TS's credential.
A backend client needs the app's permissions too, and your main backend's backendClients
decide whether it's a trusted or a scoped client:
main.go// connectBackendClient opens a Jazz session against the main backend's// /jazz as a backend client. credential returns a fresh OIDC token of// this machine's workload: Jazz asks for every request and socket.func connectBackendClient(ctx context.Context, appID, serverURL string, credential jazz.TokenProvider) (*jazz.DB, error) {permissions, err := os.ReadFile("jazz.permissions.json")if err != nil {return nil, err}return jazzapp.Open(ctx, jazz.Config{AppID: appID,ServerURL: serverURL, // e.g. "https://my-app.com/jazz"Storage: jazz.StorageMemory,Permissions: string(permissions),Auth: jazz.Credential(credential),})}
main.go// requireTrusted checks that the main backend admitted the client as// trusted (acting as the system, with ForUser), not scoped to one user.func requireTrusted(ctx context.Context, client *jazz.DB) error {kind, err := client.BackendClient(ctx)if err != nil {return err}if kind != jazz.BackendTrusted {return fmt.Errorf("this job needs a trusted backend client, not %q", kind)}return nil}
client.Shutdown(ctx) waits until ctx's deadline (10 seconds if it has none) for queued writes
to reach your main backend, then closes. With memory storage, writes still pending are lost, and
it returns jazz.ErrUnsynced with Error.Pending counting them. With persistent storage, give
each worker a DataDir of its own: one client at a time has a store open.
main.go// closeBackendClient uploads the writes the client holds, for up to 10// seconds, then closes it. With memory storage, writes that haven't// arrived by then are lost.func closeBackendClient(client *jazz.DB) error {ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()err := client.Shutdown(ctx)var unsynced *jazz.Errorif errors.As(err, &unsynced) && errors.Is(err, jazz.ErrUnsynced) {log.Printf("closing lost %d writes", unsynced.Pending)}return err}
session.close() first waits for the writes the client holds to reach the backend, for up to
10 seconds (close({ timeoutMs })). With the memory driver, writes that still haven't arrived are
lost, and close() rejects saying how many; close({ timeoutMs: 0 }) closes at once and accepts
that. Exiting the process without close() loses them too, so always await it before a script
ends. Each token
needs at least 60 seconds of validity left when Jazz uses it; one closer to expiry is refused. Each
identity can hold at most 4 sync sockets at a time for now, so keep to four workers per trusted
identity.
While your main backend is unreachable, createJazzClient waits without logging anything, so give a job
its own timeout.
A backend client reads from your main backend by default: db.all(query) (TypeScript) and
jazz.all(query) (Rust) ask the server, so a job sees what other clients wrote. While the main
backend is unreachable, such a read, and a subscription's first result, waits until it's back; it
doesn't fail or answer from the local store. Give a job its own timeout, or read local data
explicitly when an answer now matters more than a fresh one: db.all(query, { tier: "local-first" })
in TypeScript, jazz.all_with(query, ReadTier::LocalFirst) in Rust.
The session opens as whatever your main backend trusts the token as: with backend authority for a
trusted machine, or signed in as its user for a scoped one. Your main backend's API routes see the
same identity, so jazz.forReqUser(request) and jazz.accountFor(request) work for requests that
carry the token as Authorization: Bearer ….
A scoped client's user gets an account when the client first signs in, like any client sign-in.
Before that, accountFor and forReqUser in your API routes find no account for that user; call
jazz.createAccountFor(userId) in your main backend if a route needs it earlier. A trusted client
uses the system identity and needs no user account.
Act for a user
A trusted client can work as one of your users with client.forUser(userId). It returns the
database as that user, just like jazz.forReqUser(request) in your main backend: writes carry the
user's identity and are checked against that user's permissions. userId is the id your main
backend's authenticate names the user by.
digest-job.tsimport { isNoJazzAccountError } from "jazz-tools/backend";const { client } = session.getSnapshot();try {const db = await client!.forUser("user_123", { claims: { org: "acme" } });await db.insert(app.notifications, { text: "Your weekly digest" }).wait({ tier: "global" });} catch (error) {if (!isNoJazzAccountError(error)) throw error;// This user hasn't signed in yet, so they have no account to act as.}
src/main.rsuse jazz_app::Error;use jazz_app::NewTodo;// A trusted client acting for one of the app's users: its reads and// writes carry their identity, under their permissions.match job.for_user("user_123", serde_json::json!({ "org": "acme" })).await{Ok(as_user) => {as_user.insert(NewTodo::new("Follow up", false)).await?;}// The user has never signed in: no account is created for them.Err(Error::NoAccount(user)) => println!("{user} has no account yet"),Err(error) => return Err(error),}
job.for_user(user_id, claims) fails with Error::NoAccount for a user with no account yet,
and with Error::Refused when your main backend refuses the identity.
It fails with Error::BundleMismatch when your main backend names the permissions it serves and
they aren't the ones this client was opened with: open it with your app's published
jazz.permissions.json.
The session is the backend client's: on a user's handle session() is None and sign_out()
fails with Error::Unsupported.
main.go// scheduleRehearsal adds a show for userID, as that user: their// permissions apply, with claims as their claims.func scheduleRehearsal(ctx context.Context, client *jazz.DB, userID string) error {db, err := client.ForUser(ctx, userID, map[string]any{"org": "acme"})if errors.Is(err, jazz.ErrNoAccount) {return nil // They haven't signed in yet, so they have no account to act as.}if err != nil {return err}defer db.Close()account, err := db.Account(ctx)if err != nil {return err}_, err = jazzapp.Shows.Insert(ctx, db, jazzapp.NewShow{Name: "Rehearsal",Venue: "The Jazz Club",Date: "2026-12-30",Doors: "18:00",ChiefAccount: account,})return err}
client.ForUser(ctx, userID, claims) returns an error matching jazz.ErrNoAccount for a user
with no account yet, and jazz.ErrPermission when your main backend refuses the identity.
The session is the backend client's: on a user's DB, Session, OnSession, Refresh, Link
and SignOut fail with jazz.ErrNotSupported. Close that DB when you're done with the user.
forUsernever creates an account. A user with no account yet rejects with aNoJazzAccountError(code: "no_account"). They get one when they first sign in, or when your main backend callsjazz.createAccountFor(userId).- Your
authenticateisn't called, because there is no request from the user. Your declarative permissions see exactly theclaimsyou pass as the user's claims, and{}when you pass none. - If your main backend refuses the identity, for example because it was revoked,
forUserrejects with an error whosestatusis 403. - The user's reads are checked by the client itself, against the
permissionsyou opened it with, so they must match thejazz.permissions.jsonyour main backend serves. The client checks this: if its app and permissions make a different bundle from the one your main backend publishes,forUserrejects withcode: "bundle_mismatch", naming both bundle ids. Redeploy the client with the currentjazz.generated.tsandjazz.permissions.json. The client's own system reads and writes are unaffected. - Only a trusted client has
forUser. On a scoped client it throws, because that client already acts as its user. In your main backend itself, usejazz.forReqUser.
Machines without an OIDC token
Some machines can't get a platform OIDC token, such as a developer's laptop, an AWS workload signing
with SigV4, or a Cloudflare Worker. Give those your app's own credential instead, such as an API key
or a token your backend issues, and resolve it to a user in authenticate, like any other sign-in.
They then act as that user, with that user's permissions.