Next.js, Better Auth and Vercel
Build a Jazz app on the default stack, end to end on one page: Next.js, Better Auth, the thin client, deployed to Vercel.This page puts the default stack together in order: a Next.js app with Jazz in its own backend, Better Auth for sign-in with its tables in Jazz, the thin client in the browser, deployed to Vercel. The code comes from the Better Auth chat example, which is tested end to end. Each step links to the page with the details.
1. Install
Install
Terminalnpm install jazz-tools
This installs Jazz 2, which is in alpha and leaves alpha soon. 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.
Terminalnpm install better-auth ws @vercel/functions @vercel/sandbox
ws and @vercel/functions let sync use a WebSocket on Vercel, and @vercel/sandbox runs the
vercel() store. Keep Jazz's native module out of Next's server bundle:
next.config.tsimport type { NextConfig } from "next";const nextConfig: NextConfig = {serverExternalPackages: ["jazz-napi"],};export default nextConfig;
2. Schema
Let the Better Auth CLI write its tables into a schema-better-auth/schema.ts module, as described in
Better Auth:
Terminalnpx @better-auth/cli generate --config ./auth-generate.ts --output ./schema-better-auth/schema.ts --yes
It writes the better_auth_* tables. Spread them into your schema.ts, next to your own
messages table:
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(),}),});
See Defining Tables.
3. Permissions
Policies decide who may read and write each row, and live in schema.ts too. Deny everything on
Better Auth's tables, so browsers can't reach them (the adapter writes through jazz.db, with
backend authority): the generated authPermissions do that. Then add your own:
schema.tsconst { definePermissions, session, anyOf, allOf, eq } = schema;const isAdmin = eq(session.claims.role, "admin");export const permissions = definePermissions({// Denies every operation on the better_auth_* tables...authPermissions,messages: {read: { chat_id: ["announcements", "chat-01"] },insert: anyOf(allOf({ chat_id: "announcements" }, isAdmin), { chat_id: "chat-01" }),update: anyOf(allOf({ chat_id: "announcements" }, isAdmin), {chat_id: "chat-01",$createdBy: session.user,}),delete: anyOf(allOf({ chat_id: "announcements" }, isAdmin), {chat_id: "chat-01",$createdBy: session.user,}),},});
Here anyone signed in reads both rooms and writes in the general one (chat-01), only admins post
announcements, and people change only their own messages; the role comes from the claims
authenticate returns. A plain update policy (rather than updateIf and updateTo) must hold
for both the old and the new row, so a message can't be moved into the announcements room. See
Declarative Permissions.
The chat ids are literals: generate compiles policies into jazz.permissions.json, so a value
that varies per deployment belongs in session.claims (set by your authenticate), not in
schema.ts.
Then generate the app files and typed bindings:
Terminalnpx jazz-tools generate
It reads schema.ts and writes jazz.app.json, jazz.permissions.json and jazz.generated.ts,
which exports app. Commit all of them, and run it again after each change. When you change tables
a deployed version already has, it asks you to run npx jazz-tools migrations create --name <name>
first; see Migrations.
4. Jazz and Better Auth in your backend
createJazz runs Jazz inside your Next.js app, and Better Auth keeps its users and sessions in it
through the Jazz adapter. authenticate asks Better Auth who a request's session cookie belongs
to:
jazz.server.tsimport { betterAuth } from "better-auth";import { nextCookies } from "better-auth/next-js";import { admin } from "better-auth/plugins";import { createJazz, perBranch, vercel } 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" };export const jazz = createJazz({app,permissions,// Production gets one core, and each preview branch its own (on your own server: sqlite()).store: vercel({namespace: ({ environment, branch }) =>environment === "production" ? "production" : perBranch(branch),}),authenticate: async (request) => {const session = await auth.api.getSession({ headers: request.headers });if (!session) return null;const role = (session.user as { role?: string | null }).role;return {userId: session.user.id,expiresAt: Math.floor(session.session.expiresAt.getTime() / 1000),claims: { role: role ?? "member" }, // from the admin plugin below};},});export const auth = betterAuth({database: jazzAdapter({ db: async () => jazz.db, schema: app }),emailAndPassword: { enabled: true },plugins: [admin({ adminRoles: ["admin"], defaultRole: "member" }), nextCookies()],});
The role comes from Better Auth's admin plugin; leave out the plugin and claims if your policies
don't use roles. See Better Auth and
How Auth Works.
Mount Jazz under /jazz, where the browser connects by default, next to Better Auth's own route:
app/jazz/[...path]/route.tsimport { jazz } from "@/jazz.server";export const { GET, POST, DELETE } = jazz.next();
app/api/auth/[...all]/route.tsimport { toNextJsHandler } from "better-auth/next-js";import { auth } from "@/jazz.server";export const { GET, POST } = toNextJsHandler(auth);
Keep auth middleware off /jazz/ (see
Keep auth middleware off Jazz's routes).
5. The browser
<JazzProvider> opens the thin client: no Wasm, no local storage, and every query and write goes
to your backend under the signed-in user's policies. It's a client component, so render it from a
file that starts with "use client":
app/providers.tsxexport function App() {return (<JazzProvider config={{ serverUrl: "/jazz" }} signedOut={<p>Sign in to continue.</p>}><YourApp /></JazzProvider>);}// Your backend's `authenticate` decides who is signed in. After your forms// call authClient.signUp / signIn / signOut, call `refresh()` from// `useJazzSession()` and Jazz follows the backend's answer.
Sign users in with Better Auth's client as usual, then call refresh() from useJazzSession() so
Jazz follows. See Thin Client and
Signing out in every tab.
6. Read and write
A query hook keeps a component up to date, and returns the db to write with:
ChatPanel.tsxconst { data: rows = [], db } = useAll(app.messages.where({ chat_id: chatId }).select("id", "author_name", "text", "sent_at").orderBy("sent_at", "asc"),);
ChatPanel.tsxawait db.insert(app.messages, {author_name: authorName,chat_id: chatId,text: messageText.trim(),sent_at: new Date(),}).wait({ tier: "global" });
On the thin client a write shows after one round trip to your backend; wait({ tier: "global" })
resolves once the server has it. See Queries and
Writing Data.
7. Run it locally
Terminalnpx jazz-tools generatenpm run dev
Under next dev, vercel() keeps its data in a SQLite file in .jazz/local (add .jazz/ to
.gitignore), and the browser syncs over an HTTP stream; nothing else to set up. See Vercel.
8. Deploy to Vercel
Push to Git or run vercel deploy. Production gets its own Jazz core and data, and each preview
branch its own, as namespace above says; see
Production, previews and development
for sharing one preview core instead. Before real users arrive:
- Connect a Vercel Blob store to production (and one per preview environment, if previews store files), so large values don't grow the core's database.
- Set
publicUrlto the URLs your users reach/jazzat. - Set
BETTER_AUTH_SECRETand Better Auth's base URL for each environment.
See Vercel for each of these, and Testing to check your policies before you ship.