React
Provider, typed hooks and the server session.
"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BetterSupabaseProvider } from "better-supabase/react";
import { bsb } from "@/lib/supabase/client";
const queryClient = new QueryClient();
export function Providers({ children }: { children: React.ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
<BetterSupabaseProvider client={bsb} queryClient={queryClient}>
{children}
</BetterSupabaseProvider>
</QueryClientProvider>
);
}Create hooks typed for your schema once:
import { createHooks } from "better-supabase/react";
import type { bsb } from "./supabase/client";
export const { useDb, useQueries, useAuth, useSupabase } =
createHooks<typeof bsb>();function CustomerList() {
const q = useQueries();
const { data } = useQuery(q.customers.list({ select: ["id", "name"] }));
const auth = useAuth();
if (auth.status === "signed-out") return <SignIn />;
return (
<ul>
{data?.map((c) => (
<li key={c.id}>{c.name}</li>
))}
</ul>
);
}useAuth()rendersloadingon the server and during hydration, then the real state. It usesuseSyncExternalStore, so it never tears.useDb()anduseQueries()re-render when the user changes.- With
queryClient, the provider removes all better-supabase queries when the user signs out or switches accounts, and refetches them when the token's tenant or role changes, so one user's or tenant's data never shows up for the next. It usesclearOnUserChange. useBroadcast(topic, values, handlers, { invalidate })subscribes to a Realtime topic while mounted and refetches the listed tables after each message.
Auth, search, storage and presence hooks
These hooks replace the code most screens write by hand. Each reads the
provider's client, or takes { client: supabase } without the provider.
"use client";
import { useSignIn } from "better-supabase/react";
export function SignInForm() {
const signIn = useSignIn({ onSuccess: () => router.push("/") });
return (
<form
action={(form) =>
signIn.password({
email: String(form.get("email")),
password: String(form.get("password")),
})
}
>
{signIn.error ? <p role="alert">{signIn.error.message}</p> : null}
<button disabled={signIn.pending}>Sign in</button>
</form>
);
}| Hook | What it returns |
|---|---|
useSignIn() | password, otp, verifyOtp and oauth, with pending and the last error |
useSignOut() | signOut(options), with pending and error; the provider then clears cached queries |
useDebouncedSearch(initial, { delayMs }) | value and setValue for the input, the settled term, and pattern with % and _ escaped for ilike |
useSignedUrl(bucket, target, { ttl }) | a signed URL that is signed again before it expires; null pauses |
useImage(bucket, target, variant) | src, srcSet, width and height for an <img> at a bucket variant |
useUpload(bucket) | upload(target, body), progress from 0 to 1, status, abort and reset |
usePresence(topic, values, { state }) | the members on a presence topic, track and untrack |
useDebouncedSearch pairs with contains, which escapes the term itself:
where: search.term ? { name: { contains: search.term } } : {}. escapeLike
is exported for filters you build yourself.
useUpload reports real progress where XMLHttpRequest exists (browsers
and React Native): the upload goes to a signed upload URL, and abort
cancels the request. Elsewhere, and for uploads with metadata, progress
jumps to 1 when the upload finishes. The same onProgress option works on
bucket.upload() directly.
usePresence tracks the state option after the join and again when its
JSON changes; pass null to untrack. It rejoins when the user changes.
Server Actions
useAction and useActionForm call a bsb.action()
Server Action and track its ActionResult, so a component doesn't need its
own transition, pending flag and error state.
"use client";
import { useActionForm } from "better-supabase/react";
import { createCustomer } from "../customer-actions";
export function CreateCustomerForm() {
const form = useActionForm(createCustomer, {
onSuccess: (customer) => toast.success(`${customer.name} added`),
});
return (
<form {...form.formProps}>
<Input name="name" aria-invalid={form.fieldErrors.name !== undefined} />
{form.fieldErrors.name ? <p>{form.fieldErrors.name}</p> : null}
<Button type="submit" disabled={form.pending}>
Add
</Button>
</form>
);
}useActionForm(action, { onSuccess, onError, resetOnSuccess })submits the form'sFormData. The fields keep what the user typed when the action fails and clear on success (resetOnSuccess: falsekeeps them, for an edit form).fieldErrorsholds the first message per field of avalidationerror;fieldErrorsOf(error)returns the same for anyDbError.useAction(action, { onSuccess, onError })runs the action from an event handler withrun(input), which resolves with theActionResult. The input type dropsFormData, soruntakes the action's object input.pendingcovers the run and the re-render it causes,dataanderrorhold the last result, andpendingInputslists the inputs in flight, so one table row can show its own change before the server confirms it:
const roleChange = useAction(updateMemberRole);
const roleOf = (member: Member) =>
roleChange.pendingInputs.findLast((input) => input.userId === member.userId)
?.role ?? member.role;useOptimisticAction(action, { state, update, onSuccess, onError })isuseActionwith React'suseOptimistic(React 19).optimisticisupdate(state, input)while a run is in flight, and it returns tostate(theconfirmedvalue) when the run settles, so a failed action undoes itself and a successful one shows what the refreshed server render sent:
const toggle = useOptimisticAction(setDone, {
state: task.done,
update: (_done, input) => input.done,
});
<Checkbox
checked={toggle.optimistic}
onCheckedChange={(done) => toggle.run({ id: task.id, done })}
/>;- A thrown error (not an
ActionResulterror) still reaches the nearest error boundary.
createErrorMessages(messages) from better-supabase turns a DbError
into the sentence to show. It takes a message, or a function of the error,
for every error kind; leaving a kind out is a type
error, so a new kind can't fall through to a generic message.
Set the wording once and read it anywhere with useErrorMessage() from
better-supabase/react. ErrorMessagesProvider takes a resolver, so the
components never call a translation hook for their errors. A block error
carries a hint code with a default English message in
better-supabase/blocks/messages,
so the resolver below shows that message first and your own sentence for
the rest. Without a provider, useErrorMessage() returns the error's
English message.
import { createErrorMessages } from "better-supabase";
import { blockErrorMessage } from "better-supabase/blocks/messages";
import { ErrorMessagesProvider, useErrorMessage } from "better-supabase/react";
function ErrorMessages({ children }: { children: ReactNode }) {
const t = useExtracted("errors");
const kindMessage = createErrorMessages({
unauthorized: t("Sign in again to continue."),
forbidden: t("You don't have access to this."),
raised: (error) => error.message,
// ...every other kind
});
return (
<ErrorMessagesProvider
messages={(error) => blockErrorMessage(error) ?? kindMessage(error)}
>
{children}
</ErrorMessagesProvider>
);
}
// In any Client Component below the provider:
const errorMessage = useErrorMessage();
toast.error(errorMessage(result.error));Record pages
createRecordProvider(customerRecord) returns a RecordProvider and a
useRecord hook for one
generated record type. The
provider takes the record's id, the initial view the server loaded, the
writes (Server Actions) and a realtime topic; useRecord() returns
{ state, actions, meta }.
Server session
useAuth() reads the browser client, so it is loading during server
rendering. To render signed-in UI on the server, hand Client Components the
server-verified session instead: pass a bsb.claims() promise to
SessionProvider and read it with useSession().
import { SessionProvider } from "better-supabase/react";
<SessionProvider session={getSession()}>
<SideNav />
</SessionProvider>;"use client";
import { useSession } from "better-supabase/react";
export function SideNav() {
const session = useSession(); // suspends until the promise resolves
return session.kind === "user" ? <Menu claims={session.claims} /> : null;
}SessionProviderrenders from Server Components: thereact-serverbuild exports it as a client reference.SessionProviderreadscaller_authz_version()from theapischema through the client'sschema(). Passschema="public"for a client that exposes it there, so you pass the client itself and need no wrapper.- The provider joins the user's
authz:<uid>channel when the browser is idle, so the join does not compete with hydration. One channel serves every provider on the same client and user. Pass the bootstrap's live version (liveVersion={bootstrap.authzVersion}) and the first join reports it instead of callingcaller_authz_version(); only a join after a reconnect reads the version again. useSession()suspends, so keep it under a<Suspense>boundary, and create the promise inside that boundary.- The session is a plain
AuthSession(no token), the same typebsb.claims()returns.tenantOf(session)reads its active tenant (the tenant claim at the top level of the token, then inapp_metadata), on the server and in the browser.
See Cache Components for the full pattern, including role-filtered menus.
Refresh when permissions change
With the sessions module's authzVersions option, the database bumps a
user's authorization version whenever their roles or grants change and
broadcasts it on the private topic authz:<uid>, which only that user may
read. Give SessionProvider a browser client and it listens there: on a new
version it refreshes the token, then calls onAuthzChange. The page keeps
its cached shell and reloads only what the new claims change.
"use client";
import type { AuthSession } from "better-supabase";
import type { ReactNode } from "react";
import { SessionProvider } from "better-supabase/react";
import { useRouter } from "next/navigation";
import { refreshSessionCache } from "@/app/actions/session";
import { supabase } from "@/lib/supabase/client";
export function SessionRefresh(props: {
session: Promise<AuthSession>;
children: ReactNode;
}) {
const router = useRouter();
return (
<SessionProvider
session={props.session}
client={supabase}
onAuthzChange={async () => {
await refreshSessionCache();
router.refresh();
}}
>
{props.children}
</SessionProvider>
);
}"use server";
import { bsb } from "@/lib/supabase/server";
export const refreshSessionCache = bsb.refreshSessionCache;bsb.refreshSessionCache() drops the caller's own bsb.cached() entries:
the session tag, the session id tag and the authorization provider's
sessionTags. Only the visible tab refreshes the token. It tells the app's
other tabs over the better-supabase:session BroadcastChannel (channel,
false for none), and they run onAuthzChange without a second refresh. A
hidden tab that hears the broadcast itself waits until it becomes visible.
onError receives a failed refresh. authzRefresh={false} turns the
listener off, and a function decides per session: a support session reads
another user's data, so authzRefresh={(session) => !supportOf(session)}
keeps it off that user's topic. On iOS and Android, use the
SessionProvider from better-supabase/react/native instead: it follows the
app's foreground and reconnects PowerSync after the refresh
(Authorization refresh on native).
A tenant from the URL
When the tenant is part of the route (/[organizationId]/customers), the
browser client doesn't read the URL: useDb(), useQueries() and the live
hooks scope tenant tables to the tenant_id claim. Resolve the tenant on the
server and hand it down:
- Read the rows in a Server Component with
bsb.context({ tenant: organizationId }), or in a'use cache: private'function that takesorganizationIdas an argument and callsbsb.cached({ tenant: organizationId }). Pass the rows to the Client Component. - Pass
organizationIdto the Client Component as a prop, and send it in the action's input. The action scopes its context withtenant: (input) => input.organizationId, so a tenant the caller doesn't belong to grants nothing, the same as a tenant from the resolver. - Pass the same id to the live hooks:
useLiveQuery(spec, { tenant })anduseLiveCount(seed, { tenant }). Seed the count with thedbfrom the scoped context:bsb.liveCount(spec, db).
export default async function Customers({
params,
}: PageProps<"/[organizationId]/customers">) {
const { organizationId } = await params;
const customers = await getCustomers(organizationId);
return <CustomerList organizationId={organizationId} customers={customers} />;
}"use client";
export function CustomerList({ organizationId, customers }: Props) {
useLiveQuery(customersSpec, { tenant: organizationId });
const add = (name: string) => createCustomer({ organizationId, name });
// ...
}"use server";
export const createCustomer = bsb.action(
{ input: CreateCustomer, tenant: (input) => input.organizationId },
(input, { db }) =>
db.customers.create({ name: input.name }, { select: ["id"] }),
);The Realtime policy still decides which tenant topics a user may join (see live queries).
Last updated on