createServer
Repositories bound to the caller, plus explicit admin and acting-as identities.
betterSupabase from createSupabase is isomorphic and holds no secrets.
createServer(betterSupabase) is its server half: it loads the env, resolves callers and
hands out repositories bound to an identity.
import { createServer } from "better-supabase/server";
import { createPostgres } from "better-supabase/postgres";
import { betterSupabase } from "./index";
export const bsb = createServer(betterSupabase, {
postgres: createPostgres(), // optional: enables ctx.sql and actingAs()
});Per request
const ctx = await bsb.context(request);
ctx.auth; // the resolved AuthState
ctx.db; // repositories over PostgREST as the caller (RLS applies)
ctx.sql; // the same repositories over direct Postgres as the caller
ctx.supabase; // a stateless supabase-js client for storage, functions, …
ctx.apply(response); // refreshed session cookies, and bsb-primary-until after a write
ctx.cookies(); // the same cookies as CookieWrite objects, for a framework's cookie APIEach client is built on first access. For a signed-in user, ctx.db runs on
a bare PostgREST client that carries the user's token, so a request that only
queries data never builds the Realtime, Storage and Auth clients. Reading
ctx.supabase or ctx.db.$client builds the full supabase-js client.
context(request) resolves a request once: later calls with the same
refresh and cookies options return the same context, so nested
middleware and several Server Components share it. Calls that pass
tenant, stats, pinnedUntil or support build a new one.
By default context() never refreshes; run the proxy for that. For routes
that browsers call with cookies outside a proxy, context(request, { refresh: true })
refreshes an expiring session; send the new cookies with
ctx.apply(response), which also sets bsb-primary-until after a write when
read replicas are configured. The Hono, edge and oRPC (bsb.fetchHandler)
adapters do this for you, and so does
handle() in your own. To verify
a bare access token (a WebSocket's, a queue message's), use
resolveToken(bsb, token). The supabase-js client is built from the verified
token, so it makes no auth calls and keeps no state between requests.
To build several contexts from one request without verifying the token again, resolve once and pass the resolution:
const resolution = await bsb.resolve(request);
const ctx = bsb.contextFromResolution(resolution, request);When env.jwksUrl is set and auth.jwks is not, createServer fetches the
JWKS right away, so the first request verifies its token without waiting for
it. Pass prefetchJwks: false to turn that off; it is off under
NODE_ENV=test.
Warm up in register()
server.warm() (and bsb.warm() on a Next instance) opens what the first
request would otherwise wait for, in parallel: the JWKS (from the
jwksStore first), one request to <url>/rest/v1/ and to the read replica
through the server's fetch, select 1 on a pool you pass, and
initialize() on a flags client you pass. It never throws. Each step reports
its time and whether it worked, and gives up after timeoutMs (5000 by
default). From Next.js, await it in register() with warm from
better-supabase/next/instrumentation, which also logs a failed step at
warn:
import { warm } from "better-supabase/next/instrumentation";
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
const { bsb } = await import("./lib/supabase/server");
const { pool } = await import("./lib/db");
const { flags } = await import("./lib/flags");
await warm(bsb, { postgres: pool, flags });
}
}postgres takes a pg Pool (query) or a postgres sql tag
(unsafe), and flags anything with initialize(). Both are typed
structurally, so the instrumentation entry imports neither.
Once register() awaits warm(), the prefetch at creation is redundant, and
with SUPABASE_JWKS inline it does nothing either. prefetchJwks: false is
still needed in two cases: tests that count fetches, and a module that
creates the server while next build evaluates it with no Auth server in
reach.
Key cache
The key set is fetched once per process and used for 300 seconds
(cacheSeconds). For maxStaleSeconds after that (another 300 by default) a
request still uses the cached set while a refresh runs in the background.
Once that window ends, the request waits for the fetch and fails when the
fetch fails, so a revoked key is not served forever while the issuer is
unreachable. A token with a kid the cached set lacks fetches it again, at
most once every 30 seconds, so a stream of forged kid values can't hammer
the issuer. A Supabase Auth key set (/auth/v1/.well-known/jwks.json) is
never kept longer than 600 seconds, cacheSeconds and maxStaleSeconds
together, because signing keys rotate. After you revoke a signing key, call
purgeKeys(url) from better-supabase/server to forget that set (or
purgeKeys() for every set and imported secret), and the next request
fetches it again.
Env and keys
createServer reads its settings from env, the first one given wins:
- The
envoption: a loaded env fromgetEnv, or the variables themselves ({ SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY }). Variables passed this way are the only ones read; a missing one is an error, never filled in fromprocess.env. - The variables
getEnvfrom@supabase/middlewarereads: Workers bindings, thenprocess.env, thenDeno.env.
Tokens verify against the first key source that is set:
auth.jwks. Inline keys, aURL, orfalse(ornull): no keys and no lookup, so only HS256 tokens withauth.jwtSecretverify.env.jwks, fromSUPABASE_JWKS. Fill it with the output ofcurl <url>/auth/v1/.well-known/jwks.jsonso a cold start verifies without a fetch; Inline signing keys has the steps.env.jwksUrl, fromSUPABASE_JWKS_URL, else<url>/auth/v1/.well-known/jwks.json.
SUPABASE_PUBLIC_URL plays no part here; only the
MCP HTTP transport reads it.
A test server that must not see your shell's variables passes both, as in hermetic server tests.
Explicit identities
// Service role: bypasses RLS. The actor is `service`, so audit columns say so.
await bsb.admin().customers.count();
// A user, with RLS, without their token: jobs, webhooks, support tooling.
await bsb.actingAs(userId, { tenant_id: organizationId }).customers.list();actingAs runs over direct Postgres with the user's claims set for the
transaction, the way PostgREST does it, so policies see
auth.uid() = userId. It needs postgres. For support work, pass
{ actor, reason } as a third argument to record the admin: see
Impersonation.
forContext(context) does the same for a context recorded earlier, such as
job.context from the jobs block. It runs
as the context's user, sets its tenant as tenant_id and as the
better_supabase.tenant setting, and keeps an impersonating admin in act.
It returns a Result, which fails with forbidden when the context has no
user, so a job never falls back to the service role:
const db = await bsb.forContext(job.context).orThrow();A job has no token, so claims that a custom access token hook adds (a role,
an organization list) are missing. claimsFor rebuilds them when the job
runs; sub, role, tenant_id and act always come from the context:
export const bsb = createServer(betterSupabase, {
postgres: createPostgres(),
claimsFor: async (userId, context) => ({
user_role: await roleOf(userId, context.tenant),
}),
});See Jobs, webhooks and agents without a session.
dbFor(auth) and contextClient(auth) bind to an auth state you already
have, for example one resolved in a proxy. contextClient builds a user's
client with createContextClient from @supabase/server, so PostgREST,
Storage and Realtime all run as that user. A secret-key or anonymous state
without extra headers gets the server's shared client; the secret-key one is
built with createAdminClient on first use.
One server verifies each access token once while it is valid: the proxy,
every bsb.context(), getClaims() and bsb.snapshot() share one memo of
verified tokens (1000 by default, sessions: { max, ttlMs }).
bsb.sessions.evict(userId) forgets a user's tokens, and sessions: false
verifies on every call.
From a verified token to a context
When something else already verified the caller (a gateway, a proxy, a queue
message that carries the token), skip a second verification and build the
context from the result. resolveToken(bsb, token) verifies a bearer token
once and returns the AuthState; bsb.contextFor(auth) turns any
AuthState into the same context bsb.context(request) returns, with db,
supabase and the caller's claims:
import { resolveToken } from "better-supabase/server";
const auth = await resolveToken(bsb, message.accessToken);
const { db } = bsb.contextFor(auth);
await db.customers.list();Without a server, pass the claims you verified yourself to connect.
authContext(auth) builds the context from an AuthState; a hand-built one
needs at least claims, and actor and tenant when the created-by and
memberships extensions should fill them:
const db = betterSupabase.connect(supabase, {
claims,
actor: { id: claims.sub, kind: "user", role: "authenticated" },
tenant: claims.tenant_id,
});Services read the caller from db.$context, not from the client: db.$context.claims
holds the verified claims and db.$context.actor the actor, so domain code
never decodes the token again or reaches for db.$client.
Token audience
createServer(betterSupabase, { auth: { audience } }) accepts only tokens
whose aud claim matches; without it the audience is not checked. Supabase
Auth issues aud: "authenticated" to signed-in users. A resource server that
also takes OAuth access tokens issued for its own URL, such as an
MCP server, lists both:
export const bsb = createServer(betterSupabase, {
auth: { audience: ["authenticated", "https://api.example.com/mcp"] },
});Token issuer
By default a token whose iss claim is not the project's Auth URL
(<url>/auth/v1) is rejected with INVALID_ISSUER, so a token another
project signed with a shared key never verifies. A token without iss still
does. issuer replaces that check: set it to one issuer or a list to require
the claim, or to false to skip it.
A local stack is reached under more than one host. A phone or an emulator
calls http://10.0.2.2:54321 or the laptop's LAN IP while Auth signs
http://127.0.0.1:54321/auth/v1, or the other way round. When the project URL's
host is loopback or private, the default check also accepts 127.0.0.1,
localhost, [::1], 10.0.2.2 (the Android emulator) and 10.0.3.2
(Genymotion), on the same scheme, port and path. loopbackAliases adds hosts,
such as the LAN IP:
export const bsb = createExpo(betterSupabase, {
auth: { loopbackAliases: ["192.168.1.20"] },
});A public project URL accepts none of these hosts, and loopbackAliases has no
effect when issuer is set.
Shared-secret tokens
Supabase Lite signs tokens with HS256 and no key id.
createServer(betterSupabase, { backend: "lite" }) verifies those against
SUPABASE_JWT_SECRET, checking the signature, exp, nbf, aud and iss
locally, and keeps verifying tokens that carry a kid through the JWKS.
liteDriver names the Lite driver, so $rpc on SQLite returns an
unsupported error instead of a request.
Request headers
headers adds headers to every Supabase request made for a caller, for
tracing, rate limits or log fields:
export const bsb = createServer(betterSupabase, {
headers: (request) => ({ "x-channel": "web" }),
});Request and correlation ids
Every context carries a request id and a correlation id, which the
audit module records on each
row change and event. ctx.db sends them as the x-request-id and
x-correlation-id headers, and ctx.sql sets them as the transaction-local
better_supabase.request_id and better_supabase.correlation_id settings.
The request id is the incoming request's x-request-id when it is valid, else
a new UUID, kept for every context built from the same Request. The
correlation id is the incoming x-correlation-id, else the request id.
An id is valid when it has 1 to 128 characters from A-Z, a-z, 0-9 and
. _ : ; , @ / + = -; anything else is dropped. The ids are log metadata: a
client can send any value, so never use them to decide access.
requestIds changes the header names, ignores the incoming headers, or turns
the ids off:
export const bsb = createServer(betterSupabase, {
requestIds: {
requestHeader: "x-vercel-id",
correlationHeader: "x-correlation-id",
incoming: true,
generate: true,
},
});| Option | Default | What it does |
|---|---|---|
requestHeader | x-request-id | the header the request id is read from and sent as |
correlationHeader | x-correlation-id | the header the correlation id is read from and sent as |
incoming | true | reuse valid ids from the incoming request's headers |
generate | true | generate a request id when the incoming request has no valid one |
requestIds: false reads and generates nothing. Set the audit module's
requestIdHeader and correlationIdHeader options to the same header names.
A job without a request passes its own ids, and the headers option still
wins over the id headers:
const ctx = server.contextFor(auth, {
requestId: job.id,
correlationId: job.data.correlationId,
});ctx.requestId and ctx.correlationId hold the ids, for an
audit event written with a
service-role transport or a log line. The authorizer gets the request id as
context.requestId on every check (see
Authorizers).
Approval ids
An authorizer that answers approval-required returns an approval id. The
client resumes by sending the call again with that id in the header you name
with approval:
export const bsb = createServer(betterSupabase, {
authorizer,
approval: { header: "x-approval-id" },
});Without approval.header, no header is read. The id must be 1 to 256
characters from A-Z, a-z, 0-9 and . _ : ; , @ / + = -, and anything
else is dropped. It reaches ctx.approval and the authorizer's
context.approval, never the subject, so the authorizer grants only an id it
issued and someone approved. A job passes approval to contextFor instead.
Active tenant
Apps that pick the tenant from the URL or a profile, rather than a claim,
pass tenant. It returns the tenant id for a request, or undefined. The
result becomes context.tenant for the memberships extension,
the better_supabase.tenant setting for ctx.sql and the x-bsb-tenant
header (TENANT_HEADER) for ctx.db, which current_tenant_id() reads with
blocks.permissions.activeTenant: 'resolver'. See
The active tenant.
export const bsb = createServer(betterSupabase, {
tenant: (request) => request.headers.get("x-organization-id") ?? undefined,
});
const ctx = await bsb.context(request, { tenant: organizationId });context(request, { tenant }) overrides the resolver for one call.
contextFromResolution can't wait for an async resolver, so it throws unless
you pass { tenant }. Under createNext, Server Components and actions
have no request URL; pass the tenant from route params with
bsb.context({ tenant }) or bsb.cached({ tenant }) (see
The active tenant).
User data in one call
bsb.bootstrapFor(request, { rpc, args, tenant }) runs the
bootstrap_<rpc> wrapper the sessions module renders for each entry in
sessions.options.bootstrap. As the caller, it checks that the Auth session
is still active, reads the user's live authorization version and calls the
app function, in one query. Calls with the same key share one query per
request, and a revoked session evicts the user from the session memo.
const boot = await bsb.bootstrapFor<Counts>(request, { rpc: "islands" });
const access = await bsb.accessFor(request, { bootstrap: boot });
if (boot.stale) {
// The live version is ahead of the token's: a role changed since sign-in.
}
await access.can("customers.write"); // checked against the live versionauthzVersion is the live version and tokenAuthzVersion the token's authz_ver;
stale is true when the first is ahead. accessFor returns the context, the
tenant and can(permission) bound to one version: the bootstrap's when you
pass it, else the token's. gen records the schema the wrappers live in;
bootstrapSchema overrides it for every call, and schema for one.
createNext and createExpo build their bsb.bootstrap and bsb.getAccess
on these two.
Classify an Auth error
authErrorKind(error) from better-supabase/auth returns what an auth-js error means for the caller: "retryable", "session-missing", "invalid-credentials", "rate-limited", "banned" or "unknown". It reads the error's code and status first, so a 429 is "rate-limited", and keeps the message checks for older Auth servers in one table. The library's own sign-in and refresh failures use it, so an app that branches on the kind agrees with them. The entry also exports the AuthErrorKind type and imports nothing else, so a client component can use it:
import { authErrorKind } from "better-supabase/auth";
const { error } = await supabase.auth.signInWithPassword(credentials);
if (error && authErrorKind(error) === "rate-limited") {
return { retryAfter: 60 };
}Machine callers
Secret keys sent as apikey are rejected unless you enable them. Give a list
of key names to accept only some of the keys in SUPABASE_SECRET_KEYS:
// SUPABASE_SECRET_KEYS={"default":"sb_secret_…","cron":"sb_secret_…"}
export const bsb = createServer(betterSupabase, { auth: { secret: ["cron"] } });
// ctx.auth is { kind: 'secret', keyName: 'cron' }; guard with allow: ['secret']secret: true accepts any configured key. The admin client is created on the
first admin() call, so servers that never use it don't need a secret key.
For a service caller ctx.db runs with the secret key, so RLS doesn't apply,
and ctx.sql is undefined: there is no user to run as. Use bsb.admin()
for privileged repository work, or bsb.actingAs(userId) to run over Postgres
as a particular user.
Cron jobs and webhooks
Code that runs without a caller, such as a cron job or a webhook handler, gets
everything it needs from bsb.admin(). You don't need a second client from
@supabase/server/core:
| Work | Handle |
|---|---|
| Rows and database functions | bsb.admin().<model> repositories and bsb.admin().$rpc |
A bucket registered with bucket | bsb.admin().$buckets.<name> |
| Any other bucket | bsb.admin().$storage.from(bucket), e.g. .remove([path]) |
| Auth users (create, invite, ban) | bsb.admin().$authAdmin, from 0.11 |
| Anything else supabase-js does | bsb.admin().$client, the secret-key client |
export async function GET() {
const admin = bsb.admin();
const { data } = await admin.$authAdmin.listUsers({ perPage: 100 });
const stale = data.users.filter((user) => user.banned_until);
await admin.$storage
.from("exports")
.remove(stale.map((user) => `${user.id}.csv`));
return new Response(null, { status: 204 });
}All of them use the secret key and bypass RLS. Pass { as: userId } to
bsb.admin() to record that user as the actor of the writes.
Pass fetch (for example tracedFetch() from better-supabase/otel) to send
every PostgREST and supabase-js request through it. Auth refreshes use
auth.fetch.
Last updated on