Cache Components
Instant navigations, prefetching and role-aware UI with Next.js 16.4 Cache Components and Partial Prefetching.
With cacheComponents, a page is a static shell that prerenders at build
time plus dynamic holes that stream in. Auth is dynamic: it reads the request
cookie. The pattern below keeps every layout synchronous, puts each session
read behind <Suspense>, and caches it per browser session, so:
- the first load shows the shell immediately and streams the user in;
- every later navigation is instant, because the session (and data derived from it) is part of the per-session App Shell that Next.js prefetches;
- the Auth server is never called during rendering. Tokens are verified locally against the JWKS, and only the proxy refreshes them.
The Next.js example implements all of it: ten menu items, five of which only admins see.
const config: NextConfig = { cacheComponents: true, partialPrefetching: true };Partial Prefetching
partialPrefetching requires cacheComponents and changes what a <Link>
downloads. Next.js builds one shared App Shell per route and reuses it for
every link to that route, instead of prefetching each link separately.
<Link> | What the prefetch contains |
|---|---|
<Link href="/x"> | The shared App Shell: static content plus cached content that does not depend on the URL. |
<Link href="/x" prefetch> | The App Shell, plus per-link prefetching: cached content behind params, searchParams or the full URL. |
<Link href="/x" prefetch={false}> | Nothing. |
Session content read through cookies() or headers() is part of the App
Shell, because it varies per session rather than per link. URL data varies per
link, so it cannot be in the shared shell: read params or searchParams
inside a child wrapped in <Suspense>.
prefetch={true} is not free. It resolves URL-specific content with one
server invocation per prefetchable link, so use it where the click must show
that content immediately (a row that opens a detail page, a sidebar link to an
article). The default App Shell prefetch is shared and costs one render per
route. A list that adds prefetch to every row multiplies the cost by the
number of rows; prefer the default and let the detail stream, or prefetch on
intent.
prefetch={true} no longer includes uncached dynamic content. If a
destination needs that content ahead of the click, cache it with "use cache"
or leave it behind <Suspense> to stream after the navigation.
A segment can adopt Partial Prefetching on its own with
export const prefetch = "partial" while the app-level flag is off. Once the
flag is on everywhere, remove the per-segment exports with
npx @next/codemod@canary remove-partial-prefetch ./app (pass ./src/app in a
src/ project).
The Next.js example
uses the flag app-wide. Its customer, member, team and role rows keep
prefetch because the detail reads params, and so do the settings tabs,
which a user clicks through one after another. The dashboard uses the shared
App Shell.
Static shell
export const ensureStatic on a layout or page tells next build how much of
the segment must prerender, and fails the build when a change makes it block:
ensureStatic | What must be static |
|---|---|
"shell" | The App Shell a default <Link> loads. Session reads sit behind <Suspense>. |
"prefetch" | The shell plus what <Link prefetch> loads for each URL. |
false | Nothing; the segment is allowed to block. |
The level covers every segment above the export too, and a child can only
ask for more, never less. Put "shell" on the synchronous app layout and
"prefetch" on list pages whose filters live in searchParams:
export const ensureStatic = "shell";export const ensureStatic = "prefetch";createNext needs nothing extra for either level: bsb.claims() and
bsb.cached() read the session through cookies(), so a component that
calls them is dynamic and must sit inside a <Suspense> boundary, which is
what the levels check.
1. Read the session once, privately cached
bsb.claims() returns the verified caller as plain data: user, the raw
JWT claims (including your custom access token hook claims) and
expiresAt, or anon / invalid. It never contains the token or a client,
so it can leave a 'use cache: private' function and cross into Client
Components.
import "server-only";
import type { AuthSession } from "better-supabase/next";
import { bsb } from "@/lib/supabase/server";
export async function getSession(): Promise<AuthSession> {
"use cache: private";
const { session } = await bsb.cached();
return session;
}bsb.cached() sets stale to 300 seconds, so the session rides in the
route's App Shell. The token's lifetime does not cap it: the proxy refreshes
the cookie on every request, prefetches included, and bsb.evictSession()
drops the user's entries on sign-out. A signed-out view that a refresh or a
sign-in would change gets 0: an anon session whose cookie is expired or
refresh_failed, and an invalid one (for example when the JWKS was
unreachable). life: { capToToken: true } brings back the old cap at the
seconds left on the token, and 0 with fewer than 30 left. stale decides
where the result can be reused:
stale | Effect |
|---|---|
| under 30 s | Not prefetched. The navigation waits for the server. |
| 30 s to 5 min | Available to per-link prefetching (<Link prefetch={true}>). |
| 5 min or more | Part of the route's App Shell: navigations are instant. |
A private cache never stores anything on the server across requests. The result only lives in that browser's router cache.
2. Keep layouts synchronous
A layout that awaits the session holds the whole segment, children
included, behind the request. Keep the layout synchronous and give each
session-dependent piece its own boundary:
export default function AppLayout({ children }: { children: ReactNode }) {
return (
<div className="app">
<header>
<Suspense fallback={<UserMenuSkeleton />}>
<UserMenu />
</Suspense>
</header>
<aside>
<Suspense fallback={<SideNavSkeleton />}>
<AppNav />
</Suspense>
</aside>
<main>{children}</main>
</div>
);
}Pages follow the same rule. With cacheComponents on, Next.js validates
every page for an instant navigation in development, so it flags anything
that would block one without an instant export. Export instant = false
only on a segment that is allowed to block, and say why next to it:
export default function CustomersPage() {
return (
<>
<h1>Customers</h1>
<Suspense fallback={<CustomerListSkeleton />}>
<PermissionGate permission="customers.read">
<CustomerList />
</PermissionGate>
</Suspense>
</>
);
}3. Share the session with Client Components
SessionProvider takes the unresolved promise as session and
useSession() unwraps it with use(). Create the promise inside the boundary, never at the top of
a layout:
import { SessionProvider } from "better-supabase/react";
export function AppNav() {
return (
<SessionProvider session={getSession()}>
<SideNav />
</SessionProvider>
);
}"use client";
import { useSession } from "better-supabase/react";
export function SideNav() {
const session = useSession();
const visible = navItems.filter(
(item) => !item.requires || can(session, item.requires),
);
return <nav aria-label="Main">{/* links */}</nav>;
}SessionProvider can be rendered straight from a Server Component: the
react-server build of better-supabase/react exports it as a client
reference. Server Components that need the session call getSession()
directly. Within a request that hits the same private cache entry.
To pick up a role or grant change without waiting for the token to rotate,
turn on the sessions module's authzVersions option and give the provider a
browser client
(Refresh when permissions change).
4. Roles and permissions
Put roles in the token, not in a query. A custom access token
hook
copies the user's role into a user_role claim every time Auth issues a
token, so the proxy's refresh is also what picks up role changes:
create function rbac.custom_access_token_hook(event jsonb)
returns jsonb language plpgsql stable set search_path = '' as $$
declare
claims jsonb := event -> 'claims';
user_role rbac.app_role;
begin
select ur.role into user_role from rbac.user_roles ur
where ur.user_id = (event ->> 'user_id')::uuid;
if user_role is not null then
claims := jsonb_set(claims, '{user_role}', to_jsonb(user_role));
end if;
return jsonb_set(event, '{claims}', claims);
end;
$$;[auth.hook.custom_access_token]
enabled = true
uri = "pg-functions://postgres/rbac/custom_access_token_hook"Map roles to permissions in code, so the check is a pure, synchronous function that runs in the proxy, Server Components and Client Components alike:
const grants = {
admin: ["customers.read", "customers.write", "users.manage" /* … */],
member: ["customers.read"],
} as const satisfies Record<Role, readonly Permission[]>;
export function can(session: AuthSession, permission: Permission): boolean {
if (session.kind !== "user") return false;
return rolesOf(session.claims).some((role) =>
grants[role].includes(permission),
);
}Read user_role from the top-level claim, falling back to app_metadata,
and never from user_metadata, which users can edit. Hiding a menu item is
UX, not security: re-check in every Server Action (can(toSession(auth), …))
and enforce it in the database with an authorize(permission) RLS helper.
Who owns what
| Part | Owns |
|---|---|
| Supabase Auth | Identity, sessions, signing and refreshing tokens |
| Your hook (SQL) | Which claims a token carries, read from your tables |
betterSupabase.claims(schema) | Validating and typing those claims on the server |
betterSupabase.userMetadata(schema) | A typed session.userMetadata for display, never for access |
| RLS | Enforcing access with the same claims (auth.jwt()) |
| Your code or an authorization library | Mapping roles to permissions |
The hook, the schema and your policies read the same claims, so agree on
one shape. For multi-tenant apps, use the one the memberships block module
emits:
const Claims = v.looseObject({
/** Global roles, e.g. `['support']`. */
roles: v.optional(v.array(v.string()), []),
/** One entry per scope the user belongs to. */
memberships: v.optional(
v.array(
v.looseObject({
scope: v.string(), // 'tenant' by default (claims.scope)
id: v.string(),
roles: v.array(v.string()),
}),
),
[],
),
/** The active tenant; the memberships extension and RLS read it. */
tenant_id: v.optional(v.pipe(v.string(), v.uuid())),
/** Plan features per tenant, e.g. `{ [tenantId]: ['exports'] }`. */
features: v.optional(v.record(v.string(), v.array(v.string())), {}),
});tenant_id is the claim the memberships extension and
current_tenant_id() read (auth.tenant.claim in the config renames it);
memberships lets the UI switch tenants without another query. Use
v.looseObject so fields another hook adds, such as an authorization
version or extra keys on a membership, survive validation. Keep the list
short: every claim is sent with every request, and
better-supabase doctor --as <user id> warns when the hook returns more than
2 KB, and, with an authorization provider
whose hook has a budget, when the claims it lists pass it.
Using an authorization library
For more than a handful of roles, an authorization library can own the roles,
the RLS helpers and the access token hook. Plug it in as an authorization
provider, and don't add the module's
tenant hook next to its hook.
5. Optimistic redirects in the proxy
The proxy verifies the token locally anyway, so it can redirect before rendering at no extra cost:
const protect: NonNullable<ProxyOptions["protect"]> = (auth, request) => {
const { pathname } = request.nextUrl;
if (pathname === "/login" || pathname.startsWith("/api/")) return undefined;
const session = toSession(auth);
if (session.kind !== "user")
return NextResponse.redirect(new URL("/login", request.url));
const permission = requiredPermission(pathname);
if (permission && !can(session, permission))
return NextResponse.redirect(new URL("/", request.url));
return undefined;
};
export const proxy = (request: NextRequest) => bsb.proxy(request, { protect });The proxy refreshes prefetches too, so a session whose token expired is
refreshed before protect sees it, and a prefetch never caches a redirect
to /login for a user who is still signed in. Parallel prefetches with the
same refresh token share one call to Auth.
6. Data derived from the session
Per-user rows go through bsb.cached() inside a private cache, so the
query runs with the user's token and RLS decides what comes back:
export async function getCustomers() {
"use cache: private";
const { db } = await bsb.cached();
return db.customers.list({ select: ["id", "name", "status"] }).orThrow();
}bsb.cached() must be called inside your own 'use cache: private'
function: the directive has to be in app code, and Next.js keys the entry on
that function's arguments. It:
- calls
cacheLife({ stale: 300 }). Pass{ life: { stale, revalidate, expire, capToToken } }to change it. In development astalebelow 300 seconds logs a warning once, since the entry then leaves the App Shell, and below 30 that it leaves the prerender; - tags the entry
bsb:session:<user id>, sobsb.evictSession(userId)drops every cached view of that user, for example after an admin changes their role.tagsadds more tags to the entry, andbsb.evictSession(userId, { tags })drops those too. In a Server Action it also re-renders the caller's page, so norefresh()is needed. It reaches the server caches and the caller's router only: another user's browser keeps its private entries until they go stale or that user's token changes; - with
tables, tags the entry with each table's tag (bsb:<table>@<tenant>andbsb:<table>@*under an active tenant, elsebsb:<table>), so theupdateTagafter a mutation of those tables drops it and the next visit re-reads.idalso tags the row of the first table:bsb.cached({ tables: ["customers"], id }); - returns the caller's context plus
session.db,supabaseandsqlare built on first access; - scopes that context to
tenantwhen you pass one, for example from the route params. Take it as an argument of your function so it is part of the cache key:getCustomers(organizationId)callsbsb.cached({ tenant: organizationId }).
With your own cacheLife
When a scope calls cacheLife more than once, Next.js combines the calls
field by field and keeps the smallest stale and the smallest revalidate.
A profile of your own next to bsb.cached() can make the entry shorter
than 300 seconds, but not longer:
import { cacheLife } from "next/cache";
export async function getCustomer(id: string) {
"use cache: private";
cacheLife({ stale: 900, revalidate: 900, expire: 3600 });
const { db } = await bsb.cached({ tables: ["customers"], id });
return db.customers.get(id).orThrow();
}The entry goes stale after 300 seconds, the smaller stale. Prefer life on
bsb.cached() over a second cacheLife call, so one call holds the whole
lifetime:
const { db } = await bsb.cached({
tables: ["customers"],
id,
life: { stale: 900, revalidate: 900, expire: 3600 },
});Max life and render stage
life: "max" is the profile of Next.js's cacheLife("max"), { stale: 300, revalidate: 2592000, expire: 31536000 }. Use it where every write calls
updateTag, so the entry never expires on its own:
const { db } = await bsb.cached({ tables: ["customers"], id, life: "max" });stage holds the read back until a render stage. stage: "navigation" awaits
navigation() from next/cache and stage: "prefetch" awaits prefetch(),
both before the context resolves, so the read stays out of the App Shell and
out of the runtime prefetch ("navigation") or the shell ("prefetch"):
const { db } = await bsb.cached({ tables: ["customers"], stage: "navigation" });bsb.bootstrap() takes the same two options. The gates throw inside a
"use cache" scope, and a Next.js build without Cache Components and Partial
Prefetching has none. In both cases stage is skipped, the read still runs,
and development logs it once.
Entries that outlive a deploy
Next.js keys every cache entry by build, so a deploy starts every entry
again. bsb.kept() keeps a read in a store of your choice, keyed by name,
arguments, user and schema version instead, and expires it on a write. It
works inside and outside 'use cache: private'; see
Keep reads across requests and deploys.
Durable use cache entries
Next.js 16.4.6 has experimental.durableUseCacheEntries (Turbopack only). With
it on, a "use cache" entry is keyed on a hash of the function's code, the
Next.js version and the env vars the code names, instead of the build, so a
deploy that changes none of them reads the entries of the one before.
"use cache: private" entries never reach a cache handler, so the flag
doesn't touch them.
| Reader | Starts new entries after | Keeps the old entries after |
|---|---|---|
bsb.public() in "use cache: remote" | a change to your code, gen output or better-supabase | a migration that changes only policies or function bodies; another Supabase project set only in runtime env |
bsb.remote(), scope: "remote" | the same, and a new schema hash or better-supabase version in RemoteCacheKey | the same; the user, session, tenant, authorization version and share key still bound each entry |
bsb.kept() | a new schema hash, version or better-supabase version | anything else, as without the flag |
The code hash covers the whole module graph of the route, including the
generated generated.meta.js and better-supabase's built code. The env part
holds only variables the code names literally: better-supabase reads its own
by a computed name, so they never join the key, and neither do the
per-deployment VERCEL_* variables unless your code names them.
Use the flag when your remote reads are expensive and your deploys rarely
change the database: a deploy then starts warm. Keep it off, and use
bsb.kept() with a version you bump, when a migration can change what a
read returns without changing the generated files (a new policy, a changed
function body), or when previews and production share one cache handler but
use different Supabase projects. With the flag on and a shared reader,
better-supabase doctor reports BS646.
tests/next-durable-cache builds the example with the flag and checks each
row of this table.
Remote scope
'use cache: remote' keeps an entry on the server, shared across instances,
instead of in the browser. Use it for user-scoped data that is expensive to
read and fine to reuse across devices. A remote scope can't read cookies or
headers, so the caller hands its verified session over: wrap the function in
bsb.remote(), take the key it passes as the first argument, and give that
key to bsb.cached():
import type { RemoteCacheKey } from "better-supabase/next";
import { bsb } from "@/lib/supabase/server";
export const getInbox = bsb.remote(
async (key: RemoteCacheKey, folder: string) => {
"use cache: remote";
const { db } = await bsb.cached({
scope: "remote",
key,
tables: ["messages"],
});
return db.messages.list({ where: { folder } }).orThrow();
},
);The key holds the user id, the Auth session id, the tenant and the
authorization version, never the token, so Next.js keys the entry on them.
The token reaches the scope through process memory for the length of the
call only. share: "user" drops the session id so one entry serves all of
the user's devices; share: { key: (snapshot) => string } names one key for
data that is the same for every caller who gets it, and the first caller's
token reads it. tenant: (...args) => string scopes the key to a tenant from
the arguments. Support sessions never hand their token over: their remote
calls get an invalid context. Remote entries default to revalidate 300
and expire 3600 seconds.
On Vercel the remote handler is shared. Elsewhere set remoteCacheHandler
in createNextConfig() (or cacheHandlers.remote), or each instance keeps
its own copy; doctor reports that as BS608.
One database call per page
bsb.bootstrap() reads the session check, the authorization version and the
page's data in one query. Name your function in the sessions block, which
generates a better_supabase.bootstrap_<name>(args jsonb) wrapper that runs
it as the caller:
blocks: {
sessions: { options: { bootstrap: { home: "app.home_data" } } },
},export async function getHome(organizationId: string) {
"use cache: private";
return bsb.bootstrap<HomeData>({
rpc: "home",
tenant: organizationId,
redirect: "/sign-in",
});
}When the sessions block has an API schema (blocks.sessions.api or
sql.api), the wrapper is also in that schema, and gen records it so
bsb.bootstrap() calls it there. Set bootstrapSchema in createNext() or
schema on the call to pick another one.
Load a read set with the session check
List read sets instead of one function and the caller picks one per call. The
wrapper runs the chosen read set in the same query, and the answer is
reads, decoded as db.$many(readSet, params) returns it.
blocks: {
sessions: {
options: {
bootstrap: {
home: { readSets: ["customers_hub", "customer_detail"], shell: "app.home_data" },
},
},
},
}const boot = await bsb.bootstrap({
rpc: "home",
readSet: customerHub,
params: { organizationId },
});
boot.reads?.customers;shell is optional; without it data is null. The wrapper accepts only the
listed names and refuses any other with unknown read set. When another call
of the same request already ran the wrapper, such as the layout, a page call
with a read set runs only db.$many(readSet, params), so the session check
is not repeated. The old one-argument wrapper is dropped when gen renders the
new one, so run db diff after changing the option.
app.home_data(args jsonb) receives args plus the tenant. The result is
plain data (session, sessionActive, authzVersion, tenant, data, reads), so
it can cross into Client Components. When the Auth session ended,
sessionActive is false, the entry is not kept, the user's tags are evicted,
and with redirect the caller goes to /sign-in?reason=session_not_found,
or ?reason=user_banned for a banned user. endReason says which, and
reasons: { ended, banned } sets other query values, as in the proxy's
verifySession. Calls with the same arguments share one query per request.
Since the wrapper checks the session, the proxy can skip its own Auth call:
proxy({ verifySession: "bootstrap" }). A Server Component can't clear
cookies, so the proxy clears them on the next request this process serves,
such as the redirect to /sign-in. bsb.bootstrap() takes
scope: "remote" and key like bsb.cached().
require: "user" with redirect sends a caller without a user session (signed
out, an API key or a service caller) there too, with ?reason=signed_out
(reasons.signedOut changes it), and types the result as an active user
session, so boot.session.user needs no check of its own.
bsb.getAccess(boot) turns the result into the caller's context,
session, tenant, authzVersion and can(permission), without verifying
the token again.
Root params
With rootParams: { locale, brand, tenant } from next/root-params in
createNext(), bsb.locale(), bsb.brand() and bsb.tenant() read them,
and contexts fall back to the tenant root param when tenant resolves
none. Outside the root layout's segment they return undefined.
Tenant scopes for cached reads
bsb.auth(), bsb.tenant(ref) and bsb.activeTenant() are the first
statement of a "use cache: private" function. Each returns the context of
bsb.cached() with the caller, and ends the render when the caller is refused,
so the function has no null ladder.
export const getAgendaItem = cache(async (org: string, id: string) => {
"use cache: private";
const { db } = await bsb.tenant(org, permissions.agenda.read, {
tables: ["agenda_items"],
});
return await db.agendaItems.get(id).orNull();
});Tell createNext() how to find the tenant record:
export const bsb = createNext(betterSupabase, {
rootParams,
tenants: {
by: "slug",
resolve: { slug: (slug) => getOrganizationBySlug(slug) },
},
});A tenant ref is a string read as by (default id), { id }, or { slug }
for any resolver kind. The resolver returns the record, which becomes
scope.tenant, or null for an unknown tenant. The scope has db,
session, user, can(permission), and for a tenant tenant and granted.
| Caller | Result |
|---|---|
| No session | unauthorized() |
| Unknown tenant or not a member | notFound() |
| Permission refused | forbidden() |
unauthorized() and forbidden() need experimental.authInterrupts, which
createNextConfig sets; without it both end in notFound(). Next.js ends the
render with these inside "use cache: private", on a render and on a prefetch
(ADR 1252). Pass the tenant as an argument of the cached function: a Server
Action cannot read a root param, and Next.js keys the cache on the arguments.
bsb.activeTenant(permission) does the same for the tenant of
rootParams.tenant.
.orNull() on a read returns null for a not_found error and throws any
other error. .or(fallback) returns the fallback in the same case.
Pass gate: true in the options to save a round trip on a cold call. The
scope returns at once, the permission check runs beside your first read, and
db settles each read after the check. A refused caller gets a forbidden,
not_found or unauthorized error Result from the read instead of rows
(ADR 1255). Do not treat can or granted as proof before that read settles.
const { db } = await bsb.tenant(org, permissions.agenda.read, {
tables: ["agenda_items"],
gate: true,
});For data every member of a tenant reads alike, bsb.shared(ref, permission, read) checks the caller outside the cache, then returns read(tenant). Write
read as a "use cache" function of the tenant, so the database is read once
per tenant and a refused caller never reaches the entry. The library does not
create a restricted database role: read runs under the client you choose, so
filter by the tenant yourself.
async function readRoles(tenantId: string) {
"use cache";
cacheTag(`roles@${tenantId}`);
return bsb.admin().roles.list({ where: { tenantId } }).orThrow();
}
export const getRoles = (org: string) =>
bsb.shared(org, permissions.roles.read, (tenant) => readRoles(tenant.id));Fill TenantProvider from better-supabase/react in the layout with
scope.tenant, and client components read it with useTenant() instead of
taking orgSlug or organizationId props.
Permission snapshots
Read the caller's permissions once, in the compact form, and pass that one
promise across the server/client boundary. better_supabase.bootstrap_permissions()
returns { apiVersion, form: "compact", keys, tenants } where each tenant is
a bitset over keys. A page that called my_permissions per tenant now makes
one call. On the built-in role tables the function is already there.
Keep the JWT payload off client props with toSession(auth, { claims: false }).
The client reads keys from PermissionsProvider and useCan in
better-supabase/react, which accepts the compact form or the expanded lists.
At 300 keys and one tenant the full list is about 7 KB and the bitset is a
few hundred bytes. At 150 memberships, claimFormat: "summary" stores a role
index per tenant instead of a { scope, id, roles } object each, or an array
of indexes when a member holds several roles, which is what drops a 9-chunk
cookie.
Cache what the UI needs the same way. The snapshot needs the session, so read
it first, then let bsb.cached() set the tags and the lifetime:
import { bsb } from "@/lib/supabase";
import { permissionsFor } from "@/lib/permissions";
export async function getSnapshot(organizationId: string) {
"use cache: private";
const session = await bsb.claims();
const snapshot = permissionsFor(session, organizationId);
await bsb.cached({
tags: [
`permissions:${session.kind === "user" ? session.user.id : "anon"}`,
`organization:${organizationId}`,
],
});
return snapshot;
}Pass the promise to a Client Component provider without awaiting it, so the layout stays synchronous and the snapshot streams in:
import { PermissionsProvider } from "@/components/permissions-provider";
import { getSnapshot } from "@/lib/access";
export default function OrganizationLayout({
children,
params,
}: LayoutProps<"/[organizationSlug]">) {
const snapshotPromise = params.then(({ organizationSlug }) =>
getSnapshot(organizationSlug),
);
return (
<PermissionsProvider snapshotPromise={snapshotPromise}>
{children}
</PermissionsProvider>
);
}When a role or plan changes, drop the user's cached views and their snapshot in the Server Action or webhook that changed it:
bsb.evictSession(userId, { tags: [`permissions:${userId}`] });The user's token keeps the old memberships until it refreshes. Policies that read the membership tables instead of the token see the change immediately.
Outside a request, bsb.contextFromSession(snapshot) builds the same
context from a SessionSnapshot you already have (bsb.getClaims()),
without verifying the token again. null gives the signed-out context.
Record pages without my_permissions
bsb.record(type).get(), .timeline() and recordListServer need the
caller's keys for their can flags. By default they call my_permissions with
the keys the record type checks, once per call. Pass heldPermissions to
createNext to give them a source that costs no database call, such as the
snapshot above. It returns the caller's full set of keys in the active tenant,
or null when it has none, and then the loader asks my_permissions as before.
import "server-only";
import { createNext } from "better-supabase/next";
import { getPermissions } from "@/features/user/permission-snapshot";
import { betterSupabase } from "./index";
export const bsb = createNext(betterSupabase, {
heldPermissions: getPermissions,
});In the Next.js example, /customers/[id] stops making six my_permissions
calls per render and loads in two waves instead of three.
What one scope costs
Each island that misses its private cache resolves the caller again. A
verified token is remembered until it expires (up to 256 tokens per
process), so only the first scope checks the signature, and none of them
calls the Auth server. The context builds its supabase-js client and
repositories on first use, so islands that only read auth build none.
Twelve islands in one render, four of which query (pnpm --filter better-supabase bench, Apple M5 Max, ES256):
| Signature checks | Clients built | Time per render | |
|---|---|---|---|
| Before | 12 | 12 | 1.42 ms |
| After | 1 | 4 | 0.10 ms |
The database calls themselves are what's left; count them with the budget. The island pattern covers the session memo that shares the verification across scopes, even while the first one is still in flight.
Skip the request read with a session handle
Every private scope still reads cookies() or headers() and looks the
verified token up in the memo. bsb.sessionHandle() does that once, in the
page, and parks the verified session until the response is sent. Pass the
returned handle to each island and to bsb.cached({ session }):
export default async function Page() {
const session = await bsb.sessionHandle();
return (
<>
<Customers session={session} />
<Notes session={session} />
</>
);
}
async function Customers({ session }: { session: SessionHandle }) {
"use cache: private";
const { db } = await bsb.cached({ session, tables: ["customers"] });
return <List rows={await db.customers.list().orThrow()} />;
}The handle names the user, session, tenant and authorization version, never the token, so it is a sound part of the cache key. A scope with a handle reads no cookie or header, runs no verification and shares one context, and so one PostgREST client, with the other islands of the same request. Without a parked session (the response has been sent, or a support session is active, whose restrictions live in the request) the scope reads the request as before. The token memo keys by a SHA-256 digest of the token, so the process never keeps a bearer credential as a map key.
Data that is the same for every user belongs in a plain 'use cache' with
bsb.tag() and bsb.admin() (see cache tags).
Don't pass a user id into a shared 'use cache' function that uses
bsb.admin(): that bypasses RLS.
Mutations through bsb.action() call updateTag, which also clears the
client router cache, so the user sees their own write. Mutations elsewhere
(bsb.route(), webhooks) expire the tags with revalidateTag(tag, { expire: 0 }).
7. Signing in and out
Sign in and out on the server with the Next.js auth
helpers: signInWithPassword, verifyOtp, exchangeCodeForSession, verifyMfa and signOut
write the session cookies on the action's response, store the verified
session for the next render and return a checked redirectTo, so the action
ends with redirect(redirectTo) and no router.refresh().
safeRedirectPath(next, fallback) from better-supabase/server is the same
check for your own flows. postAuthPath(source, fallback) from
better-supabase/next reads ?next= from a Request, URLSearchParams or
a page's searchParams and runs that check:
redirect(postAuthPath(await searchParams, "/")).
When the browser client signs in or out instead, it writes the session cookie, and the router cache still
holds the old private session. Call a Server Action that runs refresh()
after signing in or out:
"use server";
import { refresh } from "next/cache";
export async function sessionChanged(): Promise<void> {
refresh();
}await supabase.auth.signInWithPassword({ email, password });
await sessionChanged();
router.push("/");
// `refresh()` in the Server Action expires the server cache. Prefetched
// private App Shells stay until the client refreshes too.
router.refresh();useSessionChange from better-supabase/next/client runs sessionChanged,
then router.push and router.refresh():
import { useSessionChange } from "better-supabase/next/client";
const go = useSessionChange(sessionChanged);
await supabase.auth.signInWithPassword({ email, password });
await go("/");After a change that only the next token carries, such as switching the
active organization, pass the browser client as refreshToken. The hook
refreshes the session first, so the server renders with the new claims, and
throws the refresh error instead of navigating with the old token:
const switched = useSessionChange(sessionChanged, router, {
refreshToken: supabase,
});
await switchOrganization({ organizationId });
await switched("/");Asymmetric signing keys
All of this depends on verifying tokens locally. With asymmetric JWT signing
keys (ES256 or RS256) the JWKS is public and cached, so the proxy, every
bsb.claims() and every bsb.context() verify without a network call.
Hosted projects use them by default. Locally, better-supabase doctor warns
when [auth] signing_keys_path is missing; better-supabase dev keys creates
one.
Render stages
A page renders in up to four stages. Each database read belongs to the earliest stage that can hold it; a read that lands later than it has to turns an instant navigation into a spinner.
| Stage | Rendered | Holds | APIs |
|---|---|---|---|
| 1. Static shell | At build time, once for everyone | Layout, headings, skeletons, public data | bsb.admin() inside 'use cache' |
| 2. App Shell | Once per browser session, prefetched | The session and data derived from it | bsb.cached(), bsb.claims(), bsb.liveCount(spec, db) |
| 3. Link prefetch | When a link enters the viewport | The data behind that link | bsb.tags(), read sets through db.$many |
| 4. Navigation | On click, not prefetched | Per-request and uncached data | bsb.context(), bsb.route() |
- Stage 1 can't read the request.
bsb.admin()bypasses RLS, so only use it for data every visitor may see, and tag the entry withbsb.tags()so mutations revalidate it. - Stage 2 runs once and is reused until its
staletime passes orbsb.evictSession()drops it. Keep it small: the menu, the session, a few counts. Pass thedbfrombsb.cached()tobsb.liveCounthere; without it,liveCountreads the request and moves to stage 4. - Stage 3 is where most page data goes. One read set per page keeps it
to one call, and
bsb.tags(readSet)revalidates it on any mutation of a table it reads. - Stage 4 is anything that reads
searchParams, headers or the request body, plus route handlers and actions. It is never prefetched, so budget it strictly.
Budget
Cache Components make it easy to spread one page over many islands, each
with its own 'use cache: private' read. Every island that misses the cache
is a PostgREST request, and islands that wait on each other add up to
sequential round trips. Count them instead of guessing:
import "server-only";
import { createNext } from "better-supabase/next";
import { betterSupabase } from "./index";
export const bsb = createNext(betterSupabase, {
debug: { budget: { calls: 8, waves: 2 } },
});export const GET = bsb.debugRoute();- calls are repository operations and RPCs. waves are sequential
rounds: a call that starts while another is in flight joins its wave, so
Promise.allof three reads is one wave. While collecting, the rawctx.supabaseclient counts too: each PostgREST, RPC, Storage and Edge Function request it sends is a call, named after its table,name(),storage/<bucket>orfunctions/<name>. Its Auth calls don't count. - The proxy gives every render a request id (
x-bsb-request-id, forwarded to Server Components and sent back on the document and_rscresponses).bsb.context()records into it, across all the scopes of that render. A'use cache: private'fill records on the render that runs it, and a'use cache: remote'fill called throughbsb.remote()records on the render that called it. A fill through a handle frombsb.sessionHandle()(bsb.cached({ session }),kept.as(session),getAccesswith a key) records on the render that made the handle. When renders of one session fill the same remote entry at once, the latest caller gets the calls. - A Supabase client the app builds itself (for example with
@supabase/server/core) doesn't pass through the recorder. Give itbsb.statsFetch(fetch)as itsglobal.fetch, and its PostgREST, RPC, Storage and Edge Function requests count for the current request. - Each
bsb.keptandbsb.remotecall adds an entry record to the stats route'sentries:{ id, kind, outcome, fillMs, bytes }, wherekindiskeptorremote,outcomeishit,miss,staleorwait, andfillMsis the fill time of a miss. Absb.remotecall is amisswhen its fill ran in this process during the call, and ahitotherwise. Absb.keptentry also carriesbytes, the size of its value as JSON. The entries ofbsb.cached()andbsb.public()have the kindsprivateandpublicand record only a miss, when their body runs; a hit is a visit without a miss.expiredTagslists the names of the tags the request's writes expired, next to thetagCallscount. - In development, a render that goes over
budgetlogs a warning once its calls have been idle for 250 ms. A private-cache hit makes no call, so warm navigations cost 0. - When a request has no
x-bsb-request-id, the collector falls back to the trace id oftraceparent, thenx-vercel-id, thenx-request-id, so calls from a route handler or an action still land in one record. - Stats also count verifications (token checks that missed the session
memo) and admin calls (reads and writes through the service role). A
render should verify at most once, and a page that reads as the user should
make no admin calls. In development, a render with admin calls logs a
warning. Attach an admin call to its render with
bsb.admin({}, { request })({ stats }on the server entry). bsb.route()responses carryx-bsb-db-calls: calls;waves;ms;verifications;adminCalls;tagCalls;hits;misses;fillMsdirectly. The last four are cache tag calls, cached calls served from an entry, cached calls that filled, and the milliseconds those fills took. A server action answers with a result, not aResponse, so withdebug.enabledit logs the same value asbsb.action x-bsb-db-calls: ...after it settles. Pages stream, so their headers leave before the render finishes; their totals are served bybsb.debugRoute()at the URL in thex-bsb-statsresponse header.- Outside development, collecting is off and the debug route answers 404 with
a JSON body that names the reason (
{ error, reason }). Setdebug.enabledfor e2e runs againstnext start. - A service that calls
betterSupabase.connect()itself is counted too, with no{ stats }option:connect(supabase, { claims }),connect({ executor: postgresExecutor(sql), storage })and the clientcontextFromSession()returns find the current request's recorder throughheaders(). A connection with an explicit{ stats }reports to that recorder only, and a call that runs whereheaders()isn't available (absb.public()fill, a job) is not counted on a request. decodescounts the session cookies the request parsed (a miss of the parsed-cookie memo), next toverifications.phasescounts calls per phase:actioninsidebsb.action,renderotherwise, and any name you mark withbsb.phase(). Thebsb.actionlog line ends withphases=write:2,render:3 keptHits=render:4 decodes=1.keptHitscounts the kept entries that served a read without a fill, per phase, so an action shows what its reads saved.
const allowed = await bsb.phase("authorization", () => can(user, "edit"));
const saved = await bsb.phase("write", () =>
db.notes.update(id, patch).orThrow(),
);In code, ctx.stats() and db.$stats() return the same numbers for one
context: { calls, waves, tables, ms, verifications, decodes, phases, adminCalls, tagCalls, expiredTags, entries }. The proxy's
verification is counted on the document response header; the totals of the
render itself come from the stats route.
Without a debug option, development still watches round trips: createNext
takes devRoundTripBudget (default 4, false turns it off) and warns when a
render waits on more sequential waves than that. The warning names
read sets as the fix, and
BS609 finds three or more awaited database reads
in one Promise.all. The OpenTelemetry plugin sets better_supabase.db.round_trips on each
database span.
The first request of a process
A cold function pays for module evaluation, the first warm(), the first
token check and the first database connection before it answers. To see which
part of that is better-supabase's, set debug.coldStart:
import "server-only";
import { createNext } from "better-supabase/next";
import { betterSupabase } from "./index";
export const bsb = createNext(betterSupabase, { debug: { coldStart: true } });The stats header then carries a cold= field while the process records a
step for the first time, and the first query logs one line:
x-bsb-db-calls: 0;0;0;1;0;0;0;0;0;cold=eval:96.4,ready:1310.2,create:1.8
bsb.cold eval:96.4,ready:1310.2,create:1.8,warm:212.5,claims:38.1,query:84.7| Field | What it measures |
|---|---|
eval | Milliseconds better-supabase/next took to evaluate, its own modules and the shared ones it loaded |
ready | Milliseconds from the start of the process to the end of that evaluation |
create | The first createNext |
warm | The first warm(), its steps run in parallel |
claims | The first bsb.getClaims(), which includes reading the request and verifying the token |
query | The first repository call's round trip, connection set-up included |
The fields count once per process, so a warm instance reports nothing. Modules
that better-supabase/server loaded before the next entry count in ready,
not in eval. The option collects the request stats outside development too,
the same as debug.enabled, and uses only performance.now(), so it runs on
every runtime. Pages stream, so their numbers arrive on the bsb.debugRoute()
response or in the log line; the proxy's document response carries the steps
that ran before it.
What each stage costs
A customer page that reads the customer list, its notes and tags behind
auth.can("customer.read") measures like this when it follows the stages
above (the numbers are asserted in tests/next/customer-reads.test.ts with a
fixture PostgREST):
| Stage | Database calls | Waves | Token verifications | Admin calls |
|---|---|---|---|---|
| 1. Static shell | 0 at request | 0 | 0 | 0 |
| 2. App Shell | 1 (bootstrap) | 1 | 1 | 0 |
| 3. Link prefetch | 1 (read set) | 1 | 0 | 0 |
| 4. Navigation | 1 per tab | 1 | 0 | 0 |
A nested scope that takes cached({ session }) reuses the verification of
stage 2, so stages 3 and 4 verify 0 times. A cold instance makes no admin
call while serving a user request; only bsb.admin() inside 'use cache'
(stage 1, at build time) uses the service role.
Fail CI when a page gets chattier with
expectDbBudget:
await expectDbBudget(page, {
maxCalls: 8,
maxWaves: 2,
maxVerifications: 1,
maxAdminCalls: 0,
during: () => page.goto("/customers"),
});Prove it with a simulated delay
Locally, every read is fast, so a page that waits for the database still looks instant. Delay the server's Supabase requests and the uncached reads show up as spinners:
import "server-only";
const delayMs = Number(process.env["BS_FETCH_DELAY_MS"] ?? "0");
const delayed: typeof fetch = async (input, init) => {
await new Promise((resolve) => setTimeout(resolve, delayMs));
return fetch(input, init);
};
export const bsb = createNext(
betterSupabase,
delayMs > 0 ? { fetch: delayed, auth: { fetch: delayed } } : {},
);fetch covers PostgREST and supabase-js, auth.fetch the token refreshes
and the JWKS. Under a 3 s delay, each of the three cache layers has a
signature you can assert in an e2e test:
| Layer | Lives in | First visit | Next visit | Reload |
|---|---|---|---|---|
Static shell and 'use cache' | The server, shared by every user | Instant | Instant, for every user | Instant |
'use cache: private' (bsb.cached()) | The browser's router cache, per session | 3 s | Instant, within its stale time | 3 s |
TanStack Query staleTime (useQueries()) | The browser's query cache, per tab | 3 s | Instant, within staleTime | 3 s |
The private cache is never stored on the server, so a reload pays for it
again; the shared cache is filled by the first request of anyone. Browser
queries go to Supabase directly, so delay those with Playwright's
page.route(). Time a page load to waitUntil: "commit": the load event
waits for the whole streamed document, which hides an instant shell.
Testing instant navigations
@next/playwright's instant() holds back dynamic content while its
callback runs, so you can assert on exactly what the shell or prefetch
contains. Against next start, enable the testing API for the test build
only. Set the variable while running next build: a build without it ignores
the lock, and every instant() test passes without checking anything.
experimental: {
exposeTestingApiInProductionBuild: process.env.EXPOSE_TESTING_API === "1",
},import { instant } from "@next/playwright";
import { expect, test } from "@playwright/test";
test("customers come from the per-session App Shell", async ({ page }) => {
await page.goto("/");
await instant(page, async () => {
await page.getByRole("link", { name: "Customers", exact: true }).click();
await page.waitForURL((url) => url.pathname === "/customers");
await expect(page.getByText("Road Runner Inc")).toBeVisible();
});
});For content that should stream after the click, assert that it is absent
inside the callback and visible after it. Run the tests against a production
build, never next dev, and without retries: a retry hides the regression
the test exists to catch. To check that a test can fail, remove
'use cache: private' from the function it depends on. The heading still
commits, but the rows never appear under the lock.
expectInstant from
better-supabase/testing wraps this pattern: it takes the navigation, the
locators that must be visible and absent under the lock, and an optional
database budget for the same navigation.
Last updated on