Next.js
Proxy, Server Components, route handlers, server actions and cache tags.
import "server-only";
import { createNext } from "better-supabase/next";
import { betterSupabase } from "./index";
export const bsb = createNext(betterSupabase);createNext(betterSupabase) is createServer plus the Next.js
pieces below, so bsb.admin() and bsb.actingAs() work too. It needs Next.js
16.3 or later.
Signing in and out from Server Actions (password, email links and codes, OAuth, MFA and sign-out) is on the Next.js auth page.
Next.js config
The Next.js example runs on this config:
import type { NextConfig } from "next";
export default {
reactStrictMode: true,
reactCompiler: true,
typedRoutes: true,
cacheComponents: true,
partialPrefetching: true,
experimental: {
authInterrupts: true,
globalNotFound: true,
typedEnv: true,
useOffline: true,
optimisticRouting: true,
prefetchInlining: true,
},
} satisfies NextConfig;| Flag | What it does with better-supabase |
|---|---|
cacheComponents, partialPrefetching | bsb.cached() reads in "use cache: private" render into the prefetched page; see Cache Components |
authInterrupts | forbidden() and unauthorized() render forbidden.tsx and unauthorized.tsx when a guard refuses the caller |
typedRoutes | href and redirect() take only routes the app has. next-intl's Link takes any string, so wrap it with Route hrefs |
globalNotFound | a URL no route matches renders app/global-not-found.tsx with its own <html>. A dynamic root segment ([locale]) matches every URL, so answer unknown /api paths from an app/api/[...rest] route with problemResponse |
typedEnv | next dev types process.env from the env files; validate the keys at runtime as well |
useOffline | a navigation, prefetch or Server Action that fails offline is retried when the network returns; see Offline and PWA |
optimisticRouting, prefetchInlining | on by default in Next 16.4; set so a default change shows up in your config diff |
bsb.remote() reads run in "use cache: remote". Vercel shares that cache
across instances; when self-hosting, set cacheHandlers.remote to a shared
handler, or doctor reports BS608.
TypeScript 7 works in next build: Next runs the project's own tsc, so
set typescript.ignoreBuildErrors to false and the build checks types with
the native compiler.
Proxy
import { bsb } from "@/lib/supabase/server";
export const proxy = (request) => bsb.proxy(request);
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|webp)$).*)",
],
};The proxy is the only place sessions are refreshed, and only for page
loads, client navigations and server actions, never for prefetches. With a
valid token it does nothing: no auth request, no cookie write. When it does
refresh, the new cookie is forwarded to the Server Components rendering the
same request, and the response gets no-store headers.
Protect routes with protect. Refreshed or cleared cookies are kept on the
response you return:
export const proxy = (request: NextRequest) =>
bsb.proxy(request, {
protect: (auth, req) =>
auth.kind !== "user" && req.nextUrl.pathname.startsWith("/app")
? NextResponse.redirect(new URL("/login", req.url))
: undefined,
});To combine the proxy with next-intl or other middleware, use before and
after (composition).
serverTiming: true adds a Server-Timing header: bsb-proxy (the whole
proxy), bsb-auth (resolving the session), and bsb-parse, bsb-verify,
bsb-refresh and bsb-ended for the phases that ran. A page load with a
valid token shows no bsb-refresh or bsb-ended: it made no Auth call.
A token is refreshed only when it expires within leeway
(auth.leeway, else 60). Outside that window the proxy parses the cookie
and verifies the token locally, with no fetch. After a refresh it stores the
new session in the session memo, so the
render that follows doesn't verify it again. Every request the proxy matches refreshes, prefetches included, so a
prefetch of a page whose token expired renders signed in, and protect
never caches a redirect to sign-in for it. Parallel requests that carry the
same refresh token (a burst of prefetches, or islands loading together)
share one call to Auth, so the single-use refresh token is spent once
(details). When two instances still race,
Auth answers the loser with refresh_token_already_used; the proxy keeps the
user signed in while the old token is valid instead of signing them out.
A smaller proxy bundle
better-supabase/next/proxy exports createProxy(), the same proxy without
the Server Component side of createNext. Import it in src/proxy.ts so the
proxy bundle leaves out sign-in flows, record bindings and REST resources:
import { createProxy } from "better-supabase/next/proxy";
import { betterSupabase } from "@/lib/supabase";
export const proxy = createProxy(betterSupabase, {
protect: (auth, request) =>
auth.kind !== "user" && request.nextUrl.pathname.startsWith("/app")
? Response.redirect(new URL("/login", request.url))
: undefined,
});Without the definition at all, pass the options alone. The proxy then loads no schema, no block set and no repositories, which is what keeps it small:
import { createProxy } from "better-supabase/next/proxy";
import { Claims, Profile } from "@/lib/claims";
export const proxy = createProxy({
auth: { claims: Claims, userMetadata: Profile },
});gen writes proxy-permissions.generated.ts next to permission-scopes.ts
when gen.permissionCatalog is on. It holds the permission keys in bit
order, so permissionsOf(session, tenant, { catalog: proxyPermissions }) in
protect reads the token's bitset without importing the catalog's source.
better-supabase doctor reads the trace of the last next build and reports
(BS650) when the proxy traces more than 400 KB.
createProxy(betterSupabase, options) takes the createNext options (env,
auth, leeway) and the proxy options (before, protect, after,
verifySession, serverTiming) in one object. It also exports
mutableResponse, overrideRequestHeaders, syncMiddlewareSetCookie and
serverTimingValue for a proxy that composes other middleware, and the
helpers a protect function reads: toSession(auth), permissionsOf(session)
and postAuthPath(request, fallback), so protect doesn't import the larger
better-supabase/next entry. It imports no
Node built-in, so it runs wherever the Next.js proxy runs.
The proxy reads only the definition's sessions part. It doesn't load the
connection runtime (the PostgREST executor, the query builder and the
repositories), which definition.connect() needs and which the client, the
servers and the testing helpers install when they are imported. Code that calls
definition.connect() without importing one of them throws a TypeError that
names this.
Ended sessions
An access token stays valid until it expires, even after its session is
signed out elsewhere, revoked or deleted. RLS that checks the session then
hides every row, and the app looks empty. verifySession asks Auth whether
the session still exists (GET /auth/v1/user) on document loads and on the
paths you list. When Auth answers 401 or 403, the proxy clears the session
cookies and redirects to redirect with ?reason=session_not_found, or
?reason=user_banned when Auth reports the user as banned:
export const proxy = (request: NextRequest) =>
bsb.proxy(request, {
verifySession: { redirect: "/login", paths: ["/"] },
protect,
});| Option | Default | Meaning |
|---|---|---|
paths | none | Paths checked on client navigations too, such as the page after sign-in |
redirect | none | Where an ended session goes; without it protect gets a signed-out caller |
reasons | session_not_found, user_banned | The reason query values for { ended, banned } on the redirect |
Each checked request costs one Auth request, so client navigations, server
actions and prefetches keep the local token check unless their path is in
paths. A request to redirect itself only clears the cookies. When Auth
cannot be reached or answers with a server error, the session is kept.
The resolution also carries sessionVerified: false and reason
("session_not_found" or "user_banned") for a protect that renders its
own page.
verifySession: true checks document loads without a redirect.
verifySession: "bootstrap" skips the proxy's Auth call because each page's
bsb.bootstrap()
checks session_active() in its one query instead. A session that check
finds ended has its cookies cleared on its next request through the proxy.
The proxy also copies its cookies into x-middleware-set-cookie, so the
render after a refresh reads the new token. Use
shouldCheckSession(request, options) to see whether a request is checked.
A proxy that does not use bsb.proxy can run the same check with
sessionStatus and clearSessionCookies
(details).
Watching the session in the browser
verifySession covers document loads. An app that keeps the session in
httpOnly cookies, with no browser Supabase client, also notices a revoked
session, a ban or changed claims while a page stays open with
sessionStatusRoute from better-supabase/server/accounts and useSessionWatch from
better-supabase/next/client:
import { sessionStatusRoute } from "better-supabase/server/accounts";
import { bsb } from "@/lib/supabase/server";
export const GET = sessionStatusRoute(bsb);"use client";
import { useSessionWatch } from "better-supabase/next/client";
export function SessionWatch() {
useSessionWatch({ redirect: "/login?reason=session_not_found" });
return null;
}onEnded(event) replaces the default reload for an ended session, a banned
user or a sign-out, for example to show a dialog before the redirect; a claims
change still refreshes the router.
The route answers { status, userId, fingerprint, expiresAt, support } with
Cache-Control: no-store: active, expired (the token expired and the
proxy refreshes it on the next navigation), ended, banned or
signed_out. It reads the verified claims from the cookie and refreshes
nothing unless refresh: true; verifySession: true also asks Auth whether
the session still exists, one network call per check. fingerprint is a SHA-256 of the claims that decide access (all but
exp, iat, nbf, jti and ignoreClaims) and of the running support
session, so a role or tenant change, or a support session that starts, ends
or switches target, changes it. claimsFingerprint(claims, support) computes
the same value on the server, for a page that passes it to the hook.
The hook checks on focus, when the tab becomes visible and every
intervalMs (60000) while visible. An ended, banned or signed-out session
loads redirect, or the current page so the proxy sends it to sign-in. A
claims change calls router.refresh(). Each change goes to the app's other
tabs over a BroadcastChannel (channel, false for none), which react the
same way. onChange(event) replaces the default, with event.reason
(ended, banned, signed_out, claims_changed) and event.source
(check or tab). watchSession(onChange, options) is the same watcher
without React.
Use either the hook or a browser client, not both. An app that keeps a
browser Supabase client already hears sign-outs and token changes through
onAuthStateChange, so it doesn't need useSessionWatch. Running both
reacts twice to the same change.
The hook compares claims from the session cookie, so claims_changed only
fires after something else refreshed the token: a navigation through the
proxy, or a route created with refresh: true, which refreshes a cookie
that is about to expire. sessionStatusRoute doesn't refresh by default, so
a role or tenant change reaches an open page when the current access token
rotates, not when the database changes; the sessions module's
authzVersions broadcast closes that gap
(Refresh when permissions change).
An ended session or a ban shows up once the proxy refreshes, or on the next
check with verifySession: true.
Auth outages
When a refresh fails because Auth is unreachable, times out or answers 5xx
or 429, the proxy calls onAuthOutage(event, request). The event carries
the cause ("network", "timeout" or "status"), the status for a
status outage, durationMs, and kept: true when the access token was
still valid and the caller stays signed in. When kept is false, a
Response you return replaces the proxy's response, so a signed-in user
sees a retry page instead of being sent to sign-in:
export const proxy = (request: NextRequest) =>
bsb.proxy(request, {
protect,
onAuthOutage: (event) =>
event.kept
? undefined
: new Response("Sign-in is temporarily unavailable.", {
status: 503,
headers: { "retry-after": "10" },
}),
});A rejected refresh token is not an outage: the session is cleared and
protect runs as usual. The refresh event also carries reason,
status and code for a failed refresh. withSession takes the same
onAuthOutage option outside Next.js.
Server Components
export default async function Customers() {
const { db } = await bsb.context();
const customers = await db.customers
.list({ select: ["id", "name"] })
.orThrow();
return <CustomerList customers={customers} />;
}bsb.context() is memoized per request with React cache(), so layouts and
pages share one context. It verifies the token locally and builds a
stateless client; no auth call happens during rendering.
bsb.context({ tenant }) scopes the context to a tenant from the route
params, in place of the memberships resolver, which has no request URL here.
The tenant gets the same checks as the resolver's
(the active tenant), and each
tenant gets its own memoized context. bsb.cached({ tenant }) does the same
in a private cache; pass the tenant in as an argument of your function.
bsb.require(options) is bsb.context() for a page only some callers may
see. It takes the same allow, aal and scopes as bsb.route(), plus
requireTenant and authorize (see server actions), and
turns a refusal into the Next.js interrupt: unauthorized() renders the
nearest unauthorized.tsx, forbidden() the nearest forbidden.tsx. Both
need experimental.authInterrupts in next.config.ts; without it, a
refused caller gets notFound().
export default async function AuditPage() {
const { db, tenant } = await bsb.require({
requireTenant: true,
roles: ["admin"],
});
const events = await db.auditEvents
.list({ where: { organizationId: tenant } })
.orThrow();
return <AuditLog events={events} />;
}bsb.require() reads the request, so it keeps the page out of the
prefetched App Shell. For a page under
Cache Components, check the
privately cached session instead and call forbidden() yourself.
bsb.liveCount(spec) counts on the server and returns a serializable
{ spec, count } seed for useLiveCount, so a badge renders with its
number and then stays current over Realtime. See
live queries.
Session
const session = await bsb.claims();
if (session.kind === "user") session.claims.user_role;bsb.claims() is the same verification without the clients: an
AuthSession of user (with user, claims and expiresAt), service,
anon or invalid. It never includes the token, so it is safe to return
from 'use cache: private' and to pass to Client Components through
SessionProvider. toSession(auth)
converts any AuthState the same way, for example inside bsb.action().
Use bsb.claims() (or jwtClaims in a pipeline entry) as the per-request
check, in place of supabase.auth.getUser(). It verifies the token locally
against the project's JWKS and never calls the Auth server, the check
@supabase/ssr recommends with getClaims(). Call getUser() only in the
flows that must see a user the Auth server has revoked or deleted since the
token was issued, such as changing a password or deleting an account. The
user on the session comes from the claims, so it works with either cookie
encoding.
The signed-in user and AuthGate
bsb.user() returns the user as plain data, { id, email, name, organizationId }, or null for anyone else. It never returns the token or the
session. Call it inside a 'use cache: private' function: it sets
cacheLife({ stale: 300 }) and the session tags like bsb.cached(), so the
user rides in the App Shell.
import "server-only";
import { bsb } from "@/lib/supabase/server";
export async function getUser() {
"use cache: private";
return bsb.user();
}AuthGate from better-supabase/next/auth-gate is a Server Component for the
app layout. The layout stays synchronous: the gate renders a <Suspense>
around one getUser() promise and hands it to useUser() in Client
Components, keyed on the user id so a user change never shows the last user's
DOM.
import { AuthGate } from "better-supabase/next/auth-gate";
import { getUser } from "@/features/auth/auth-queries";
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<AuthGate
user={getUser}
fallback={<AppShellSkeleton />}
redirect="/sign-in"
>
{children}
</AuthGate>
);
}"use client";
import { useUser } from "better-supabase/next/auth-gate";
export function AccountMenu() {
const user = useUser();
return <span>{user?.email}</span>;
}useUser() uses use() on the promise, so render it under a <Suspense>
boundary. redirect sends a signed-out visitor away, and refuse answers with
forbidden() or unauthorized() instead. The proxy still does the cookie-only
redirect before rendering; the gate is the second check. A check function
runs before the first <Suspense> when the status code must be set there, but
awaiting a request API in it makes the layout dynamic.
Taint
With experimental.taint: true in next.config.ts, createNext calls React's
experimental_taintUniqueValue on the access token and the refresh token of
each request, and experimental_taintObjectReference on the auth state, the
server context and the bsb.admin() context. A Server Component that passes
one of them to a Client Component then fails with React's taint error instead
of leaking it into the page. createNextConfig() from @better-supabase/next-config
turns the flag on. Taint is the second layer: return plain data such as
bsb.user() first. Without the flag, or on a React build without the API,
the calls do nothing. The Supabase clients a context creates are not tainted.
With cacheComponents enabled, see Cache Components
for instant navigations and role-aware menus, and the
island pattern for pages with many private
Suspense islands. Every scope of one request shares a single verification
through bsb.getClaims().
Route handlers
export const GET = bsb.route<{ id: string }>((request, { db, params }) =>
db.customers.get(params.id, { select: ["id", "name"] }),
);allowcontrols who gets in; the default is['user']. Use['user', 'anon']for public routes or['service']for machine callers. Anonymous users (signInAnonymously()) get a 403 withcode: "ANONYMOUS_USER"unlessallowlists'anonymous';'anon'means no session and never admits them, so a public route that serves guests too uses['user', 'anonymous', 'anon'].- Return a
ResultorAsyncResult(as above, noawaitneeded), a plain value, or aResponse. Errors, thrownDbExceptions and rejected callers become Problem Details responses; a 401 carries aWWW-Authenticatechallenge. Any other thrown error is a 500 without internal details (unlessexposeErrors), whileredirect()andnotFound()still reach Next.js.
Middleware entries
toNextRoute(entries, handler) and toNextAction(entries, action) run an
array of @supabase/middleware entries around a
route handler or a Server Action, for code that composes the Supabase entries
(withRequiredClaims, withSupabaseClient, withCors) instead of
bsb.route():
import { withCors } from "@supabase/middleware/cors";
import { withRequiredClaims } from "@supabase/server/middleware/required-claims";
import { withSupabaseClient } from "@supabase/server/middleware/client";
import { toNextRoute } from "better-supabase/next";
export const GET = toNextRoute(
[
withCors({ origin: "https://app.example.com" }),
withRequiredClaims(),
withSupabaseClient(),
],
async (_request, ctx) => (await ctx.supabase.from("notes").select()).data,
);The handler returns a Response or a value (sent as JSON, undefined as
204), and gets the route params as its third argument. Response-phase
entries see its response, so withCors adds its headers to it, including on
the 401 withRequiredClaims sends a caller without a session.
toNextAction builds the request from headers(), so the entries read the
session cookie, and writes the cookies they set through cookies().set. When
an entry answers first, such as withRequiredClaims with a 401, the action
doesn't run and the call throws NextActionRejected with that status and
response:
"use server";
import { withRequiredClaims } from "@supabase/server/middleware/required-claims";
import { withSupabaseClient } from "@supabase/server/middleware/client";
import { toNextAction } from "better-supabase/next";
export const addNote = toNextAction(
[withRequiredClaims(), withSupabaseClient()],
async (ctx, body: string) => {
await ctx.supabase.from("notes").insert({ body });
},
);REST resources
createResources(bsb)(map, options) from better-supabase/next/resources
serves the same REST routes as
Hono resources from one catch-all route.
It returns a handler for each method, and lives on its own subpath so an app
that serves no resources does not ship the router:
import { defineAction } from "better-supabase/next";
import { createResources } from "better-supabase/next/resources";
import { bsb } from "@/lib/supabase/server";
export const { GET, POST, PATCH, PUT, DELETE } = createResources(bsb)(
{
customers: {
operations: ["list", "get", "update", "delete"],
select: ["id", "name", "status", "organizationId"],
actions: {
archive: defineAction({
method: "POST",
path: "/{id}/archive",
summary: "Archive a customer",
handler: (ctx, { id }) =>
ctx.db.customers.update(
String(id),
{ status: "archived" },
{ select: ["id", "status"] },
),
}),
},
},
},
{ basePath: "/api/v1" },
);basePath is the path of the catch-all route. An unknown path answers 404
before auth resolves. The options also take the guards of bsb.route
(allow, aal, scopes), and refresh: true refreshes an expired session
cookie (off by default, because the proxy refreshes the routes it matches).
permissions on a resource and permission on an action are decided by the
authorizer passed to createNext. See Resources
for hooks, actions and permissions, and API documents to
serve the matching OpenAPI document.
The OpenAPI document
Keep the map in its own module, so the routes and the document read the same
object and can't drift. satisfies checks the map against ResourceMapOf<typeof bsb>
without widening it:
import type { ResourceMapOf } from "better-supabase/next/resources";
import type { bsb } from "@/lib/supabase/server";
export const API_BASE_PATH = "/api/v1";
export const apiResources = {
customers: { operations: ["list", "get", "update", "delete"] },
projects: { operations: ["list", "get", "create", "update", "delete"] },
} satisfies ResourceMapOf<typeof bsb>;import { createOpenApi } from "better-supabase/spec";
import { API_BASE_PATH, apiResources } from "@/features/api/api-resources";
import { betterSupabase } from "@/lib/supabase";
const document = createOpenApi(betterSupabase, {
info: { title: "My API", version: "1.0.0" },
basePath: API_BASE_PATH,
resources: apiResources,
});
export function GET(): Response {
return Response.json(document);
}A static segment wins over the catch-all, so /api/v1/openapi.json sits next
to /api/v1/[...path]. The document describes every column of a model,
including ones select leaves out of the responses.
An action's data is typed from its input schema when you build it with
defineAction. With an explicit database type, pass all three type
arguments: defineAction<Db, string, typeof Input>({ ... }).
Bearer callers
Route handlers serve OAuth clients, agents and other apps that send
Authorization: Bearer <token>. A token from the
Supabase OAuth server
carries client_id and scope; a token exchanged for an agent carries an
RFC 8693 act chain. The session names who acts for the user:
| Token | session.actor | session.delegation |
|---|---|---|
| The user's own | not set | not set |
client_id: 'c1', scope: 'openid customers:read' | { id: 'c1', kind: 'oauth-client' } | { scopes: ['openid', 'customers:read'] } |
act: { sub: 'agent', act: { sub: 'mcp-42' } } | { id: 'agent', kind: 'oauth-client', chain } | { scopes, chain } |
act: { kind: 'support', sub, session_id, read_only } | { id, kind: 'support', sessionId, readOnly } | not set |
act: { kind: 'impersonation', sub, reason } | { id, kind: 'impersonation', reason } | not set |
The outermost sub is the current actor; nested levels are the actors
before it, kept on chain for the audit log. A support session or an
impersonated session marks its act with kind (see
impersonation). An act
that is not a chain of objects each with a non-empty sub, or has another
kind, resolves to { kind: 'invalid', reason: 'actor' } and a 401, never
to the user alone.
scopes on a route limits what a delegated token (an oauth-client actor)
may do. The user's own session is not limited, and neither is a support or
impersonated session, which acts as the user:
export const GET = bsb.route<{ id: string }>(
(request, { db, params }) =>
db.customers.get(params.id, { select: ["id", "name"] }),
{ scopes: ["customers:read"] },
);Bearer callers get Problem Details for every refusal:
| Case | Status | Header |
|---|---|---|
| No token | 401 | WWW-Authenticate: Bearer realm="supabase" |
A token that does not verify, or a malformed act chain | 401 | WWW-Authenticate: Bearer realm="supabase", error="invalid_token" |
A delegated token without a scope in scopes | 403 | WWW-Authenticate: Bearer realm="supabase", error="insufficient_scope", scope="customers:read" |
| A row RLS hides from the user | 404 | none |
RLS still decides the rows: the token's sub is the user, so a client sees
at most what the user sees. scopes is accepted by bsb.action, the edge,
Hono and oRPC guards too.
Server actions
"use server";
export const createCustomer = bsb.action(
{ input: customerInput }, // any Standard Schema: zod, valibot, arktype
(input, { db }) => db.customers.create(input, { select: ["id"] }),
);The action accepts a plain object or FormData, validates it, and returns a
serializable ActionResult: { ok: true, data } or { ok: false, error },
where error is a plain DbError your form can render (validation
errors carry issues with paths). tenant: (input) => input.organizationId
scopes the action's context to a tenant from the validated input.
useActionForm and useAction call
it from a Client Component.
requireTenant and authorize run after allow, aal and scopes, so
the permission check sits next to the action instead of at the top of its
body:
export const inviteMember = bsb.action(
{
input: Invite,
requireTenant: true,
authorize: (session, input) => canAssign(session, input.role),
},
(input, { db, tenant }) =>
db.invitations.create({ ...input, organizationId: tenant }),
);canAssign stands for your own check, for example one your authorization
provider exports.
requireTenant: truerefuses a caller without an active tenant with aforbiddenerror (code: "NO_TENANT") and typesctx.tenantas astring. The tenant is the action'stenant, then the server'stenantresolver, then the tenant claim.permissionnames a permission theauthorizerpassed tocreateNextmust grant, checked afterrolesand beforeauthorize. The resource the authorizer sees is{ type: "action", properties: input }for an action and{ type: "route" }forbsb.route(); passresource: (input, ctx) =>to load the row it acts on instead (see Load the resource). A denial isforbiddenwithcode: "PERMISSION_DENIED"(orAPPROVAL_REQUIRED) and the permission key; without an authorizer, every caller is refused (see Authorizers).authorize(session, input)gets theAuthSessionand the validated input (the request, inbsb.route()). Returningfalserefuses the caller withforbidden(code: "NOT_AUTHORIZED").ctx.sessionis the caller'sAuthSession, so the body doesn't calltoSession(ctx.auth)again.bsb.route(handler, { requireTenant, authorize })takes the same options and answers a refusal with a 403 Problem Details response.
Route handlers and actions pass event sink sends they started to after()
from next/server, so the function stays alive until the sends finish (see
event sinks).
With support in the server options, bsb.startSupport({ targetUserId, reason })
and bsb.stopSupport() start and end a support session
from an action: they set or clear its cookie, and every read after that
renders as the target. bsb.cached() reads add a bsb:support:<id> tag
(supportTag(id)), so ending the session drops the target's cached pages.
Block actions
bsb.blockAction(client, method, options) is an action that calls one block
method as the caller. It runs the same guard, validation, permission and
authorize checks as bsb.action, and its result is typed from the method's
data. Without args the validated input is the method's only argument;
args(input, ctx) returns the arguments when the method takes anything
else, and TypeScript requires it then.
"use server";
import * as v from "valibot";
import { permissions } from "@/lib/supabase/blocks.generated";
export const createTask = bsb.blockAction(({ db }) => db.tasks, "create", {
input: v.object({ title: v.pipe(v.string(), v.minLength(1)) }),
requireTenant: true,
permission: permissions["tasks"].write,
args: (input, { tenant }) => [tenant, input],
});The client is built per call from the request's context, so the block runs
as the signed-in user. A refused caller, a failed validation and a database
error all come back as { ok: false, error }, like any other action.
A fourth argument maps the data of a success, so the client receives only
what it reads and not the whole row. tags still sees the method's own data:
export const publishAdvisory = bsb.blockAction(
({ db }) => db.advisories,
"publishAdvisory",
{
input: v.object({ id: v.pipe(v.string(), v.uuid()) }),
requireTenant: true,
permission: "advisories.publish",
tags: () => [tags.advisories()],
refresh: true,
args: ({ id }) => [{ id, status: "final" }],
},
(advisory) => advisory.id,
);Write args with a parameter ((_) => [...] when it reads nothing):
TypeScript infers a callback without parameters before it knows the
method, and then the arguments don't type as the method's tuple.
Bound arguments, guards and results
bsb.action takes four more options. bound is a schema for the leading arguments of action.bind(null, id); tenant(input, bound) and the body fn(input, ctx, bound) read the validated tuple. guard(tenant, ctx) runs after authentication and the permission check and before the body, and a returned DbError refuses the call. invalidates lists tables whose cache tags drop after a successful call, as on bsb.blockAction. result(outcome) maps the ActionResult before it returns and may be async:
export const archive = bsb.action(
{
bound: v.tuple([v.string()]),
input: v.object({ reason: v.string() }),
tenant: (_input, [organizationId]) => organizationId,
guard: (_tenant, { auth }) =>
auth.kind === "user" ? undefined : dbError("forbidden", "Sign in first"),
result: (outcome) => outcome,
},
({ reason }, { db }, [organizationId]) =>
db.projects.archive({ organizationId, reason }),
);
// <form action={archive.bind(null, organizationId)}>tags computes cache tags to expire after a successful call, from the
tenant, the validated input and the returned data, and refresh: true calls
refresh() from next/cache afterwards, so the caller no longer refreshes the
router itself:
export const createAgendaItem = bsb.action(
async (input, { db }) => await db.agendaItems.create(input),
{
input: agendaItemSchema,
tenant: (input) => input.organizationId,
tags: ({ tenant }) => [agendaTag(tenant)],
refresh: true,
},
);evictSession: true drops every cached entry of the caller after a successful
call (bsb.evictSession) and re-renders their page. Use it for a write that
changes what other domains read, such as a membership, role or profile change,
and prefer tags when the write reaches one domain:
export const renameOrganization = bsb.action(
async ({ name }, { db }) => await db.organizations.rename(name),
{ input: renameSchema, evictSession: true },
);Mapping the data to another type
result keeps the data type. To return a different type, pass a mapper as the
third argument of bsb.action. It receives the data of a successful body, may
be async, and its return type becomes data of the ActionResult. It runs
after the invalidates tags drop, so a mapper that throws a DbException
turns into the action's error without leaving a stale cache:
export const createNote = bsb.action(
{ input: v.object({ title: v.string() }), invalidates: ["notes"] },
({ title }, { db }) => db.notes.insert({ title }),
(row) => ({ id: row.id, href: `/notes/${row.id}` }),
);Rules every action shares
createNext({ actions }) holds what each action would repeat (ADR 1256).
envelope(outcome) returns fields merged into every outcome, such as a
translated message, and each action's return type carries them. guard
runs before an action's own guard. from(value) settles a value the library
does not know, such as a better-result Result.
export const bsb = createNext(betterSupabase, {
actions: {
envelope: (outcome) => ({
message: outcome.ok ? "Saved" : translate(outcome.error),
}),
guard: (tenant, ctx) =>
ctx.auth.kind === "user" && isReadOnly(ctx) ? readOnlyError : undefined,
},
});On the client, render ActionDefaultsProvider from better-supabase/react in a
Client Component with onSuccess and onError callbacks. useAction,
useOptimisticAction and useActionForm call them with the whole outcome when
the call has no callback of its own, so a toast needs no startTransition
block. defineTags(["customers"]) returns tags.customers(tenant), one tag
function that a reader's tags option and an action's tags both use.
The app's own context
bsb.withContext((session, base) => ({ ... })) returns cached, getAccess and action that hand back the app's context merged into the library's. The factory runs once per request and tenant, from the session the library already read. It may be async: each call awaits it, and concurrent calls on one context share a single run.
export const app = bsb.withContext(async (session, base) => ({
organizationId: base.tenant,
plan: await loadPlan(base),
}));createNext keeps the schema's Database type, so ctx.supabase is SupabaseClient<Database> in all of them.
Cache tags
Every mutation invalidates bsb:<table>, its tenant's bsb:<table>@<tenant>
and bsb:<table>:<id>: with
updateTag inside server actions (read-your-writes), and with
revalidateTag(tag, { expire: 0 }) elsewhere, so the next read after a
write in a route handler waits for fresh data instead of serving the stale
entry. Tag your cached reads to match:
async function publicPlans() {
"use cache";
const { db } = await bsb.public({ tables: ["plans"] });
return db.plans.list({ where: { public: true } }).orThrow();
}bsb.public() reads as the anon role, so Row Level Security decides what the
cache may hold, and it tags the entry itself. Use bsb.admin() only for data no
policy describes. BS640 reports a plain "use cache"
function that reads cookies, headers or bsb.cached(). Writes from outside the
process expire these tags through a signed route.
Caching user data
"use cache" functions cannot read cookies or headers. Cache public reads
there with bsb.public(). Per-user reads stay on bsb.context(), which is
already deduplicated per request; with Cache Components, wrap them in "use cache: private"
(how).
Tenant-scoped tags
A read scoped to one tenant can say so, so a mutation in another tenant leaves it cached:
async function customerList(tenant: string) {
"use cache";
const spec = betterSupabase.spec.customers.list({
where: { organizationId: tenant },
});
bsb.tags(spec, { tenant });
return bsb.admin().$run(spec).orThrow();
}The read is tagged bsb:customers@<tenant> and bsb:customers@*. A
mutation invalidates bsb:customers, the tag of its tenant (from the
request context, such as the memberships extension's), or bsb:customers@* when it
has none, and the tags of the rows it changed. Reads without a tenant keep
bsb:<table>, which every mutation of the table invalidates, and so does a
read across tenants ({ tenant: "*" }), which carries bsb:<table> as well
as bsb:<table>@*. bsb.tag
takes the same option as its third argument, and tagFor(table, undefined, { tenant }) builds the tag.
Tags and private caches
Tags reach the cache scope that stores the entry. A "use cache" or "use cache: remote" entry lives on the server, so updateTag and revalidateTag invalidate it for every caller. A "use cache: private" entry never persists on the server across requests: the browser's client router keeps it for the stale time of its cacheLife. A mutation in a server action clears the whole client cache, because Next.js clears it when an action calls updateTag, revalidateTag, revalidatePath or refresh. A mutation in a route handler or a webhook does not reach a browser that already holds the entry, so give private entries a finite stale time that you can accept as the delay.
Payload RPC tables
bsb.bootstrap({ rpc }) tags its entry with the tables the bootstrap_<rpc> payload reads, so bsb:<table>@<tenant> invalidation reaches it. Declare them on the entry, as model keys:
blocks: {
sessions: {
options: {
bootstrap: {
home: { function: "app.home_data", tables: ["customers", "notes"] },
},
},
},
},Without tables, gen reads the function body (pg_proc.prosrc) and records the known tables it names after from, join, update or into. A table a function reaches through another function or a dynamic statement needs to be declared. bsb.bootstrap({ rpc, tables }) adds more tables for one call.
Turn invalidation off with createNext(betterSupabase, { cacheTags: false }). The
invalidation is the nextCache() cache adapter;
attach others with betterSupabase.cache(adapter). To serve stale entries
while they revalidate after writes outside an action, turn cacheTags off
and attach nextCache({ revalidate: "max" }) yourself.
A redirect() or notFound() after a write in bsb.action() or
bsb.route() still sets the replica pin cookie and keeps the event sends
running.
Record bindings
A record page's bindings have their own cache tags,
so a write to one binding keeps the others cached.
bsb.record(customerRecord) takes a
generated record type and
returns get(id, options?) and timeline(id, options?) for Server
Components, actions, one Server Action per binding write, each of which
drops its binding's tags, and tags(id, tenant?), the record tag and each
binding tag, for your own cached reads.
| Function | Tag |
|---|---|
recordTag(subject, { tenant? }) | bsb:record@<tenant>:<type>:<id>, the header and badges |
bindingTag(subject, binding, { tenant? }) | the record tag plus #<binding> |
invalidateBinding(subject, binding, options?) | drops both: updateTag in a server action, revalidateTag elsewhere |
import { recordTag, bindingTag } from "better-supabase/next";
import { cacheTag } from "next/cache";
async function customerFiles(tenant: string, id: string) {
"use cache";
const subject = { type: "customer", id };
cacheTag(
bindingTag(subject, "attachments", { tenant }),
recordTag(subject, { tenant }),
);
const result = await loadFiles(tenant, subject);
if (!result.ok) throw result.error;
return result.data;
}Export the actions your UI calls from a "use server" file. Each takes
{ id, input }, checks the caller's permission for the write, and calls
invalidateBinding with the request's tenant after a successful write:
"use server";
import { customerPage } from "./customer-record";
export const removeCustomerAttachments =
customerPage.actions.attachments.remove;Last updated on
Overview
One adapter per framework runs withBetterSupabase in its middleware, so every route, loader and action gets the caller's repositories.
Next.js auth
Sign in, send and verify email links and codes, OAuth with PKCE, MFA and sign-out from Server Actions, with the session visible in the same request.