SvelteKit + Supabase: cookie-based SSR client in hooks.server.ts, per request
SvelteKit agents either skip SSR auth entirely or share one client across requests. The current docs pattern: createServerClient per request in hooks.server.ts with the SvelteKit cookie interface, browser client in the load functions that run client-side.
SvelteKit + Supabase: per-request server client via hooks.server.ts
SvelteKit renders on both sides, so agents pick one client and use it everywhere. That breaks in both directions: the browser client has no cookies on the server, and a shared server client leaks sessions between requests.
Checkable procedure
- Install
@supabase/supabase-jsand@supabase/ssr. - In
hooks.server.ts, create the server client per request withcreateServerClient, wiring its cookie interface to SvelteKit'sevent.cookies:getAllfromevent.cookies.getAll(),setAllwriting back throughevent.cookies.set(). - Expose the session/user on
event.localsin the handle function soloadfunctions and server routes can read auth state without rebuilding clients. - In
+layout.ts(the universal load), create the browser client withcreateBrowserClientfor client-side navigation. Serverloadfunctions (+page.server.ts) use the request-scoped server client fromlocals. - Verify with
supabase.auth.getClaims()on the server before trusting who the user is.getSession()on the server reads an unverified cookie.
The leak to check for
A client created at module scope in $lib/ and imported by +page.server.ts files is shared across requests. Symptoms are intermittent: user A occasionally sees user B's data, usually under load when requests overlap. The fix is always the same, create it inside the request handler.
Quick test
Two browsers, two users, hit a server-loaded page that shows the email at the same time. Then expire the access token and confirm navigation still works, the hooks refresh keeps the session alive.
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.