Expo Router
Server loaders, API routes and middleware that verify the caller and run as them.
import { createExpo } from "better-supabase/expo";
import { betterSupabase } from "./index";
export const bsb = createExpo(betterSupabase);createExpo(betterSupabase) is createServer plus the
pieces Expo Router's server output needs. It reads the bearer token first and
the session cookie second, and verifies the JWT locally. Install
expo-server (58.1 or later, Expo SDK 58) next to better-supabase, and set
web.output to "server" in app.json. That turns on data loaders,
middleware and server rendering, so a loader sees the caller's cookie:
{
"expo": {
"web": { "bundler": "metro", "output": "server" },
"plugins": ["expo-router", "expo-secure-store"]
}
}The unstable_ options of the expo-router plugin that SDK 57 needed are
deprecated in SDK 58 and have no effect; remove them when you upgrade.
expo-secure-store is the
plugin for secureStorage on the device; add
expo-notifications too when you use the push block.
Loaders
bsb.loader(fn, options) returns a route loader that runs fn as the
caller, so RLS applies to every read:
import { useLoaderData } from "expo-router";
import { bsb } from "../../lib/supabase/server";
export const loader = bsb.loader(
({ db }) => db.customers.list({ select: ["id", "name"] }).orThrow(),
{ allow: ["user"] },
);
export default function Customers() {
const customers = useLoaderData<typeof loader>();
// ...
}- A caller
allowrefuses throws aStatusError(401 or 403) that Expo Router answers. - A
DbExceptionfrom.orThrow()becomes aStatusErrorwith the error's status, so a missing row answers 404 with the Problem Details as the body. - During static rendering there is no request, so the loader throws. Read
public data without a caller in a loader built with
createStaticLoaderfromexpo-server. - Loader data is serialized to JSON. Select the columns the screen shows, and convert Temporal values to strings before returning them.
bsb.request(request, options) returns the same server context for code that
isn't a loader.
With expo-server's loader helpers
bsb.loader returns an expo-server LoaderFunction, so it works anywhere a
loader does. When a route already uses createServerLoader, call
bsb.request inside it instead:
import { createServerLoader } from "expo-server";
import { bsb } from "../../lib/supabase/server";
export const loader = createServerLoader(async (request, params) => {
const { db } = await bsb.request(request, { allow: ["user"] });
const customer = await db.customers
.get(String(params.id), { select: ["id", "name"] })
.orThrow();
return { customer, country: request.headers.get("cf-ipcountry") };
});bsb.request throws the same StatusError for a refused caller. It doesn't
map a DbException from .orThrow(), so a missing row there is a 500 unless
you catch it; use bsb.loader when you want that mapping.
To add your own step around every loader, wrap bsb.loader in a function that
returns a LoaderFunction:
import type { LoaderFunction } from "expo-server";
import { bsb } from "./server";
export function timedLoader<T>(
name: string,
fn: Parameters<typeof bsb.loader<T>>[0],
): LoaderFunction<T> {
const loader = bsb.loader(fn, { allow: ["user"] });
return async (request, params) => {
const started = performance.now();
try {
return await loader(request, params);
} finally {
console.info(name, Math.round(performance.now() - started), "ms");
}
};
}For public data on routes that are rendered at build time, use
createStaticLoader((params) => ...) from expo-server. It gets no request,
so it can't run as a caller; read only data that every visitor may see.
Reading the session and the page data in one call
bsb.bootstrap(request, { rpc }) runs the bootstrap_<rpc> wrapper the
sessions module renders for sessions.options.bootstrap: one database call
returns whether the session is still active, the live authorization version,
the token's version and the page's data. The layout and page loaders of one
navigation share the call for 10 seconds, keyed on the request, the session
and the arguments, so a layout and a page that both bootstrap make one round
trip. A signed-out caller makes no call.
blocks: {
sessions: {
options: {
authzVersions: true,
bootstrap: { islands: "public.island_counts" },
},
},
},export const loader = bsb.loader(
async (_ctx, _params, request) => {
const boot = await bsb.bootstrap<IslandCounts>(request, { rpc: "islands" });
const access = await bsb.getAccess(request, { bootstrap: boot });
return {
counts: boot.data,
stale: boot.stale,
canWrite: await access.can("customers.write"),
};
},
{ allow: ["user"] },
);| Field | What it holds |
|---|---|
session | The verified caller |
sessionActive | false once the Auth session was revoked; data is then null |
authzVersion | The user's live authorization version, read in the same call |
tokenAuthzVersion | The authz_ver the token carries |
stale | The live version is ahead of the token's |
tenant | The active tenant the call ran for |
data | What the function returned |
getAccess with bootstrap checks permissions against the live version, so
a role taken away since the token was issued is already gone in this loader.
Pass args for the function's arguments and tenant for a tenant from the
route's params. gen records the wrapper's schema (the API schema when
the config sets sql.api); bootstrapSchema in the server options or schema
on the call overrides it.
Caching loader results
bsb.cached(request, { tables, tags, tenant }) returns the request's context
and the tags an app-side cache should store a loader's result under: the
user's session tag, the authorization provider's session tags, the tag of the
Auth session and the table tags of tables. Calls for the same request share
one context.
export const loader = bsb.loader(async (_ctx, params, request) => {
const { context, tags } = await bsb.cached(request, {
tables: ["customers"],
tenant: String(params.org),
});
return appCache.remember(tags, () =>
context.db.customers.list({ select: ["id", "name"] }).orThrow(),
);
});Purge the cache when a write invalidates those tags. Attach a
cache adapter to the events hub,
and build the tags a mutation invalidates with cacheTagsOf from
better-supabase/server:
import { cacheTagsOf, sessionTag } from "better-supabase/server";
betterSupabase.cache({
name: "app-cache",
invalidate: (target) => appCache.purge(cacheTagsOf(target)),
});
// After a role change, drop the user's own entries too.
appCache.purge([sessionTag(userId)]);API routes
bsb.handler(fn, options) turns a function into an API route handler.
Results become JSON or Problem Details, and
undefined becomes 204:
import { bsb } from "../../lib/supabase/server";
export const GET = bsb.handler((_request, { db }) =>
db.customers.list({ select: ["id", "name"] }),
);toExpo(entries, handler) runs an @supabase/middleware entry array around
an API route instead. The handler gets the request, the contributions and the
route parameters, and returns a Response:
import { toExpo } from "better-supabase/expo";
import { withBetterSupabase } from "better-supabase/server";
import { bsb } from "../../lib/supabase/server";
export const GET = toExpo([withBetterSupabase(bsb)], async (_request, ctx) =>
Response.json(await ctx.db.notes.list().orThrow()),
);Middleware
bsb.middleware() in +middleware.ts refreshes an expired cookie session
before loaders run and writes the new cookies with setResponseHeaders. From
0.11 it also hands that session to the loaders and bsb.request calls of the
same request, so they read the refreshed session without calling Auth again,
even with refresh: false. A loader that runs without middleware refreshes on
its own, so the middleware is optional for routes that only need a loader.
Either way a request makes at most one Auth call.
import { bsb } from "../lib/supabase/server";
export default bsb.middleware({ redirectTo: "/sign-in", allow: ["user"] });With redirectTo, a caller allow refuses is sent there with the original
path in next. Without it the middleware only refreshes the session. Bearer
tokens are never refreshed.
Client entries
Screens import the client from one of two entries. better-supabase/client
is the web client, for Expo web and any browser code.
better-supabase/client/native is the one for iOS and Android: it takes
secureStorage and works without the DOM.
Both load without a global TextEncoder or TextDecoder; better-supabase
creates them when it first signs or decodes a token.
Jest and jest-expo
better-supabase is ESM-only on purpose, so jest-expo has to transform it.
Add better-supabase to the allow-list in transformIgnorePatterns:
module.exports = {
preset: "jest-expo",
transformIgnorePatterns: [
"node_modules/(?!(?:.pnpm/)?((jest-)?react-native|@react-native(-community)?|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|better-supabase))",
],
};A jsdom test environment can lack TextEncoder and TextDecoder. Importing
better-supabase does not need them, but a test that decodes a session does:
polyfill both in setupFiles with the ones from node:util. The
testing page has the same section.
Native screens
Loaders and middleware run on the server for web requests. iOS and Android use the React Native client and, for offline reads, a PowerSync database. The Expo example runs one list definition on both, and its organization switcher reads the synced memberships, so it lists the user's organizations offline.
Social sign-in
On iOS and Android, sign in with Apple or Google through the native SDK
(expo-apple-authentication, @react-native-google-signin/google-signin)
and pass its ID token to supabase.auth.signInWithIdToken on the native
client. There is no browser redirect, so no PKCE callback route. The session
lands in secureStorage, and API routes verify its access token like any
other. Supabase's guides cover the provider setup for
Apple and
Google.
Session snapshot
In an API route, bsb.snapshot(request) returns the verified user, shared by
every call with the same token, and bsb.contextFromSession(snapshot) builds
a context from it with no second verification:
export async function GET(request: Request) {
const { db } = await bsb.contextFromSession(await bsb.snapshot(request));
return Response.json(await db.notes.list().orThrow());
}A snapshot holds the access token: never return it in a response. A copy
of it (a spread, structuredClone, a serialized loader result) gets the
invalid context, so pass plain values such as the user id onward instead.
Prefetches refresh the session too. Parallel requests with the same refresh
token share one call to Auth, so they never race on it.
Last updated on