Vercel
Learn how to run Jazz inside your Next.js app on Vercel, with each environment's data in its own Sandbox.On Vercel, your Next.js app is the whole deployment. The vercel() store keeps each namespace's
data (production, a preview branch, …) in a persistent Vercel Sandbox that your functions
start on demand. There's no separate service to set up and no secrets to copy.
This page sets up your main backend: the backend that runs createJazz, serves sync to your
browsers and apps, and decides who each user is. Other trusted machines reach Jazz through it as
backend clients.
Install
Terminalnpm install jazz-tools
This installs Jazz 2, which is in beta. Versions before 2.0 are
Classic Jazz, which has a different API: projects on jazz-tools 0.x
and guides that use co.map, CoValue or Group are Classic.
Set it up
Install the Sandbox SDK next to jazz-tools:
Terminalpnpm add @vercel/sandbox
Use the vercel() store:
jazz.server.tsimport { createJazz, perBranch, vercel } from "jazz-tools/backend";import { app } from "./jazz.generated";import permissions from "./jazz.permissions.json" with { type: "json" };export const jazz = createJazz({app,permissions,// Production gets one core, and each preview branch its own.store: vercel({namespace: ({ environment, branch }) =>environment === "production" ? "production" : perBranch(branch),// Where the cores run and keep their data: your functions' region.region: "iad1",}),authenticate: async (request) => {const session = await getSession(request); // your own authif (!session) return null;return {userId: session.user.id,expiresAt: Math.floor(session.session.expiresAt.getTime() / 1000),};},});
app(fromjazz.generated.ts) defines your schema, andpermissions(yourjazz.permissions.json, imported as JSON) defines who can access the data. Your backend uses the versions your code imports (so rolling back your application also returns to the schema and permissions of that version).authenticate(request)reads your own session (a cookie, a header) and returns{ userId, expiresAt, claims? }(expiresAt: when that session expires, in Unix seconds), ornullwhen signed out. Jazz uses it for every operation that needs authentication: sign-ins, sync connections andforReqUser. If your provider issues JWTs,fromJWT()is a ready-madeauthenticate. See How Auth Works in Jazz.- Admin and backend routes never leave the process: from outside, only sync and sign-in are
reachable under
/jazz. createJazzopens nothing when your module loads: the store opens on first use, such as the first request orjazz.dbcall, and there's one Jazz per store per process. So it's safe at a module's top level everywhere, including Next.js, whose build and dev workers import your modules too.await jazz.ready()opens it right away, for a server that should fail at startup rather than on its first request.
In a Next.js app, install ws and @vercel/functions (both also needed under next dev) and keep
Jazz's native module out of Next's server bundle:
Terminalnpm install ws @vercel/functions
next.config.tsimport type { NextConfig } from "next";const nextConfig: NextConfig = {// Your backend loads Jazz's native module; Next must not bundle it.serverExternalPackages: ["jazz-napi"],};export default nextConfig;
Mount it with a catch-all route under /jazz, where clients connect by default:
app/jazz/[...path]/route.tsimport { jazz } from "@/jazz.server";export const { GET, POST, DELETE } = jazz.next();
Then deploy as usual with git push or vercel deploy. Your functions authenticate to Vercel with
their own OIDC token, and the core's secrets are generated inside the Sandbox, so Jazz needs no
environment variables of its own. Your auth may: Better Auth, for example, needs
BETTER_AUTH_SECRET in each environment.
Jazz's native module comes in one package per platform, @garden-co/jazz-napi-linux-x64-gnu on
Vercel, which npm installs as an optional dependency of jazz-napi. npm 10 can leave it out of a
package-lock.json written on a Mac, when the lockfile was regenerated over an existing
node_modules. The deployment then fails with "Jazz NAPI artifact is missing. Install
@garden-co/jazz-napi-linux-x64-gnu@…". To keep it in the lockfile whatever machine writes it, list
it in your app's own optional dependencies, at your jazz-tools version:
package.json{"optionalDependencies": {"@garden-co/jazz-napi-linux-x64-gnu": "<your jazz-tools version>"}}
On Vercel, sync uses a WebSocket (through upgradeWebSocket from @vercel/functions). Under plain
next dev, which can't upgrade sockets, the browser
switches to an HTTP stream on its own.
Install ws. Without it, the backend still builds and starts, and logs once at startup "jazz: next()
on Vercel needs the ws package: npm install ws. Without it, sync sockets can't open: clients sync
over the HTTP stream instead." Clients still sync then, but the HTTP stream needs a single instance
or sticky routing.
Set publicUrl to the URLs browsers reach /jazz at. Without it, the backend takes its URL from
each request's headers, and logs "createJazz: vouched for a device account of …, taken from the
request's headers. Set publicUrl …" the first time a device account signs in. With publicUrl set,
the backend accepts device accounts only for the URLs it lists and refuses others with a warning
("refused a device account whose proof is for …"), so list every URL your users reach /jazz
at, a second custom domain included. Device accounts belong to one origin: a guest on your
production domain and one on a deployment URL are different accounts, while signed-in users see the
same data on every URL. Vercel's system environment variables name the production domain and the
current deployment's URLs:
jazz.server.tsexport const jazz = createJazz({// …publicUrl: [process.env.VERCEL_PROJECT_PRODUCTION_URL,process.env.VERCEL_BRANCH_URL,process.env.VERCEL_URL,].filter(Boolean).map((host) => `https://${host}/jazz`),});
Your auth library needs storage that outlives a function call. Better Auth with a local SQLite file, as in its quick start, loses its users on Vercel: give it a hosted database, or keep its tables in Jazz with the Jazz adapter.
Connect the browser
The browser talks to /jazz on the same origin by default and signs in with your app's own
session cookie:
App.tsx<JazzProvider config={{ serverUrl: "/jazz" }} signedOut={<SignIn />}><App /></JazzProvider>
The client asks your backend who is signed in: authenticate answers, and the client gets the
account, identity and claims as plain data. It asks again when the app starts, when the page regains
focus and when another tab signs in or out. Your backend decides who is signed in; after your own
sign-in or sign-out, call refresh() from useJazzSession() and the session follows its answer. Every sync connection asks authenticate again, so a
sign-out on the server or changed claims apply without client code. See
How Auth Works in Jazz.
Trusted backend use
jazz.db acts with backend authority: it sees and writes everything, so check access in your own
code first. Use it for system work: jobs, webhooks, migrations, admin routes.
import { jazz } from "./jazz.server";import { app } from "./jazz.generated";await jazz.db.insert(app.auditLog, { event: "invoice.paid" });
User-scoped use
await jazz.forReqUser(request) runs your authenticate and returns a database with that user's
policies and authorship. It's the default for anything a user triggers: route handlers, server
actions, server components. Concurrent requests stay isolated.
app/api/todos/route.tsimport { jazz } from "@/jazz.server";import { app } from "@/jazz.generated";export async function GET(request: Request) {const db = await jazz.forReqUser(request);return Response.json(await db.all(app.todos));}
For a signed-out request, forReqUser throws a RequestAuthenticationError (code: "signed_out").
Map it to a 401 rather than a 500:
import { isRequestAuthenticationError } from "jazz-tools/backend";try {const db = await jazz.forReqUser(request);// …} catch (error) {if (isRequestAuthenticationError(error)) return new Response(null, { status: 401 });throw error;}
When a route acts with backend authority on a user's behalf (placing an order the user can't write
directly, say), await jazz.accountFor(request) names that user's account, or null when signed
out or when the user has no Jazz account yet, so the backend's db can write rows that point at it.
Users without an account
Your backend never creates an account on its own. A user gets one when they sign in from a Jazz
client, when a guest links to them, or when you call
jazz.createAccountFor(userId). Until then, forReqUser and withAttribution throw a
NoJazzAccountError (code: "no_account", with the userId), and accountFor returns null.
For users who never open a client, such as API-only users, webhooks or imports, create the account yourself, for example in your sign-in route. It returns the account id, and calling it again returns the same one:
const user = await authenticate(request);if (!user) return new Response(null, { status: 401 });const account = await jazz.createAccountFor(user.userId);
Once a user has an account, a guest can no longer link to them, so don't call createAccountFor in
a sign-up flow whose browser may hold a guest's device account. To tell the error apart, use
isNoJazzAccountError(error) from jazz-tools/backend.
A browser whose user no longer has an account on the core, for example after a reset dev store or on a new core, signs in again when sync refuses it, instead of reconnecting forever.
Backend clients
Other trusted machines, such as a job runner, a worker on another cloud or a partner's service,
connect to this backend's /jazz as backend clients, with their own
machine-to-machine credential. List the ones you trust in createJazz({ backendClients }).
Large values
Large values, such as files and long streams, are stored in chunks, which can live outside the
core's database. On Vercel, vercel() picks where they go:
- Vercel Blob, when a Blob store is connected to the project (the Storage tab in the Vercel
dashboard sets
BLOB_STORE_ID). A store created through the Vercel API or CLI sets onlyBLOB_READ_WRITE_TOKEN, so pass its id asvercelBlob({ storeId }). Nothing else to set up: browsers send and fetch large values through your/jazzroute, and the core reads and writes the blobs itself with your function's OIDC token. Blobs are private, and each is checked against its SHA-256 when read. - The core's SQLite file on its Drive, when no Blob store is connected. This works, but the file grows with every large value, and the backend logs a warning saying how to connect one.
To choose yourself, pass blobs:
jazz.server.tsimport { s3, vercel, vercelBlob } from "jazz-tools/backend";// `namespace` and `region` as in "Set it up" abovevercel({ namespace, region }); // Vercel Blob if a Blob store is connected, otherwise SQLitevercel({ namespace, region, blobs: vercelBlob({ storeId: "store_..." }) }); // a specific Blob storevercel({ namespace, region, blobs: s3() }); // an S3 bucket connected through the Vercel Marketplacevercel({ namespace, region, blobs: "sqlite" }); // always the core's SQLite file
s3() reads S3_BUCKET_NAME, AWS_REGION and AWS_ROLE_ARN, which the Marketplace's AWS
integration sets, and the core assumes that role with your function's OIDC token. The bucket can be in
any region: on Vercel, AWS_REGION is the function's region, so if it doesn't match the bucket, the
backend learns the bucket's region from S3's first reply, signs for it from then on, and logs a
warning suggesting you set AWS_REGION to it. Putting the bucket in the core's region still
keeps latency and transfer costs down, and the backend warns when it knows the bucket is elsewhere. Its options are the same
as for your own server.
Each Blob store or bucket serves one Vercel environment. A store you connect spans every
environment unless you limit it, so create one store per environment, connect each to its own
environment only, and enable OIDC for each environment in the project's settings. With the CLI,
name the environment when you create the store, for example
vercel blob create-store my-app-production --access private --environment production --yes.
Without --environment, a store created through the CLI or the API is connected to production,
preview and development alike, and a second one then fails with project_env_var_not_unique. A core given another environment's store refuses to start, for
example "Blob store … serves the production environment, not preview; connect a separate Blob store
to each environment". Both vercelBlob() and s3() also take a prefix, by default
jazz/<store id>/.
Where large values go is a one-way choice. A core that started on SQLite can move to Vercel Blob or S3 later: connect a store and redeploy. The core then moves the chunks already in its SQLite file to the new store in the background, which uses compute and storage operations until it's done; how long that takes depends on how much is stored in SQLite. Every other change, including disconnecting or swapping the Blob store, moving between Vercel Blob and S3, or moving back to SQLite, is not supported yet and the core refuses to start.
Upload files from the browser with db.insertStreaming(..., file.stream()), which goes through
/jazz (see Uploading and downloading files),
not through a route of your own: Vercel refuses a function request body over 4.5 MB with
413 FUNCTION_PAYLOAD_TOO_LARGE, so an upload route that passes request.body to
insertStreaming works locally and fails on Vercel. Downloads through your own route are fine.
History keeps every version of a row, so deleting rows doesn't free their large values, and there is no way to erase them yet. Expect blob storage to only grow.
A change to the vercelBlob() or s3() options doesn't reach a core that is already running the
same jazz-tools version. It applies the next time the core starts: after it stops when idle, or
when you deploy a new jazz-tools version.
Production, previews and development
namespace decides which core, and so which data, a deployment uses. Each core is a Sandbox named
jazz-<VERCEL_PROJECT_ID>-<namespace> with its own Drive. The function gets the deployment's
environment ("production", "preview", or a custom environment's slug) and its Git branch.
Pick one of these setups:
jazz.server.tsimport { perBranch, vercel } from "jazz-tools/backend";// Production, and one core per preview branch: each branch starts with its own data.vercel({namespace: ({ environment, branch }) =>environment === "production" ? "production" : perBranch(branch),region: "iad1",});// One core per Vercel environment: every preview shares one core, as a staging environment// (a custom environment such as "staging" gets its own).vercel({ namespace: ({ environment }) => environment, region: "iad1" });
- Per branch isolates each pull request: a migration or test data on one branch never reaches
another.
perBranchgives the same core names as earlier versions, so existing preview cores keep their data. A preview deployed withvercel deployor through the API has no branch unless the Vercel project is connected to a Git repository, even when you run the CLI inside a checkout. Such a preview has no branch to name, and the store throws when it opens; useperBranch(branch) || "cli-previews"to give such previews a core of their own. - Shared keeps one set of preview data that all branches see. It needs fewer cores, but the branches share one schema history too, so a schema change or migration deployed from one branch applies to the data every preview uses.
- Production's core is never shared. A core trusts the environment whose deployment started it
first and refuses the others. So a fixed string namespace isn't a setup: whichever environment
deploys first pins the core, and if a preview starts it first, production's own deploys are
refused. Name production's core from
environment, as both setups above do.
To reset a preview's data, delete its Sandbox and the Drive attached to it (the one it mounts at
/data) in the Vercel dashboard. This can't be undone. Production's Sandbox and Drive are in the
same list with similar names, and a long preview Drive name is shortened with a hash, so check the
Sandbox's name (jazz-<project>-<namespace>) and pick the Drive from the Sandbox itself. The next
request creates both again, with an empty database and a new app ID. Large values already in Vercel Blob or S3 stay there; delete them from the store if you
need to. Nothing deletes the cores of merged or deleted branches yet.
Blob stores follow environments, not namespaces: connect one store to production and one to preview (see Large values).
When vercel() opens, it logs which core it uses once per process, for example
jazz: store vercel namespace "production" (core jazz-prj-…-production).
Local development
Outside Vercel, vercel() uses a local store instead, by default sqlite({ path: ".jazz/local" }).
Only production and preview deployments use the Sandbox: next dev, vercel dev and an
environment pulled with vercel env pull all run against a SQLite file on your machine. Pass local to
choose a different one, such as vercel({ namespace, region, local: sqlite({ path: ".jazz/dev" }) }) to keep data you
already have.
Add .jazz/ to .gitignore.
Use vercel() in development too, rather than switching to sqlite() yourself: sqlite() refuses
to start on Vercel, which has no lasting disk.
Only one process can open a SQLite directory at a time. If a second one tries, it fails with an
error saying another process holds the directory, usually a second dev server. Stop it, or give
each server its own path.
Options
namespace and region are required; the other options are optional.
| Option | Default | What it does |
|---|---|---|
namespace | required | Which core a deployment uses: a string, or a function of { environment, branch }; see Production, previews and development |
region | required | Where the core's Sandbox runs and its Drive keeps the data; see Region |
vcpus | 1 | Sandbox size, 2 GB of memory per vCPU |
maxDriveBytes | 10 GiB | The most data the environment's Drive holds |
idleMs | 5 minutes | How long the Sandbox stays up with no requests or clients |
coreTarballUrl | the Linux jazz-napi package for your installed jazz-tools version | Which Jazz core build the Sandbox runs |
blobs | vercelBlob() if a Blob store is connected, otherwise "sqlite" | Where large values go; see Large values |
local | sqlite({ path: ".jazz/local" }) | The store used outside Vercel |
vercel() without namespace throws when it's called, in next dev too, and names the usual
choices. The namespace is lowercased, other characters become -, and the whole Sandbox name may be
at most 128 characters (about 90 for the namespace); an empty or longer one throws. environment
and branch come from Vercel's system environment variables, which are exposed by default. While
vercel() throws, the browser stays on its loading state, so check the function logs when a
deployment never finishes loading.
Upgrading from name: vercel({ name }) now throws, and when it can, the error gives the exact
namespace to use. A name of the form jazz-<project>-<rest> becomes namespace: "<rest>", where
<project> is your Vercel project ID lowercased, with each run of characters other than a-z and
0-9 turned into one - (prj_AbC1 becomes prj-abc1). A name of any other form (myapp-core,
uppercase letters, the raw prj_… ID) can't be reached by a namespace: that core keeps its data,
but this version opens another one, and the error says so. Without name, earlier versions used
the per-branch setup above, which keeps those cores. Copy that one when upgrading: the
one-core-per-environment setup (as on the home page) moves previews onto a new, empty core.
The default coreTarballUrl covers every published jazz-tools version, release candidates
included; set it only for a build you made yourself. If the Sandbox can't download the core, the
function's error says so and the Sandbox is stopped. A Sandbox that already holds another
app's core is refused.
Region
region is the Vercel region where each core's
Sandbox runs and its Drive keeps the data. Pick the region your functions run in (the project's
Function Region setting): every request to the core goes from the function to the Sandbox, so a
core in another region adds a round trip between the two to each one. When the two differ, the
backend logs a warning once per process naming both regions.
A core's region is fixed when it's created. Moving an existing core to another region isn't
supported yet (#5441): it needs its data copied.
If region doesn't match where an existing core's Sandbox (or Drive) is, the store throws when it
opens, naming the core's region, rather than using it anyway or creating an empty core elsewhere.
vercel() without region throws when it's called, in next dev too. Earlier versions created
every core in iad1, so region: "iad1" keeps existing cores and their data where they are.
Upgrading: add region: "iad1". Core and Drive names don't depend on the region, so the same
cores open with their data.
Limits
- Each namespace gets one persistent Sandbox and its Drive. Two apps in one Vercel project need
namespaces that differ per environment too, for example
({ environment }) => `chat-${environment}`. The smallest size is 2 GB of memory and 1 vCPU. - Nothing cleans up the Sandboxes and Drives of merged or deleted branches yet; delete them in the Vercel dashboard.
- The first request in an environment takes longer: it creates the Sandbox and downloads the Jazz server onto the Drive. Vercel's own checks of a new deployment can make that first request, or wake a stopped Sandbox, so the cold start may already be over when you first open the page.
- The Sandbox stops after 5 minutes with no requests and no connected clients; a connected client keeps it awake, even when idle. The next request wakes it, which took 0.6 to 1 s in our benchmarks and 4.2 s on a real project; requests after the wake took about 0.45 s.
- Vercel ends a function's WebSockets at the route's
maxDuration(300 s by default). Just before that,jazz.next()closes each sync socket and clients reconnect at once. To reconnect less often, raise the limit in the route file withexport const maxDuration = 800;(Pro plan). - A redeploy on the same
jazz-toolsversion doesn't disturb connected clients. Deploying a newerjazz-toolsrestarts the core on that version, which briefly drops open sockets; clients reconnect. An older deployment that is still running never moves the core back. - A thin client resends unanswered writes after its socket reconnects, and each lands once; a
transaction in flight at the drop ends with
ThinConnectionLostError. See Pending writes. vercel()needs Next.js 16 for now: under Next 15's webpack build, every request fails with "Cannot find module 'jazz-tools/package.json'".