React Router
Run withBetterSupabase as React Router server middleware, with the caller's repositories in loaders and actions.
toReactRouter(entries, key) from better-supabase/react-router returns a
server middleware. It sets every key
withBetterSupabase contributes under a
createContext() key, and the response next() returns passes back through
the entries, so refreshed session cookies reach the browser. Turn on
future.v8_middleware in react-router.config.ts first.
import { createContext } from "react-router";
import {
type BetterSupabaseContributions,
createServer,
withBetterSupabase,
} from "better-supabase/server";
import { toReactRouter } from "better-supabase/react-router";
import { betterSupabase, type Functions, type Models } from "./index";
const bsb = createServer(betterSupabase);
export const supabase =
createContext<BetterSupabaseContributions<Models, Functions, unknown>>();
export const supabaseMiddleware = toReactRouter(
[withBetterSupabase(bsb, { refresh: true, allow: ["user", "none"] })],
supabase,
);import { supabaseMiddleware } from "./lib/supabase/middleware.server";
export const middleware = [supabaseMiddleware];Loaders and actions read the contributions from context:
import { supabase } from "../lib/supabase/middleware.server";
export async function loader({ context }: Route.LoaderArgs) {
return context.get(supabase).db.notes.list().orThrow();
}A guard refusal returns the 401 or 403 Problem Details instead of calling
next(). Put allow: ["user"] on a middleware in the routes that need a
signed-in user. The bridge makes the request body readable twice, so an entry
and an action both see it.
better-supabase init detects React Router framework mode from @react-router/dev, sets gen.hooks to react-router and writes lib/supabase/middleware.server.ts, unless the file exists. Turn on future.v8_middleware and export middleware from app/root.tsx yourself.
Session snapshot
The helpers from createReactRouter(betterSupabase) hand every loader
locals.snapshot, the verified user, so a loader can build a context with
bsb.contextFromSession(locals.snapshot) and no second verification:
export const loader = bsb.loader({}, async (_args, locals) => {
const { db } = await bsb.contextFromSession(locals.snapshot);
return 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