Alpha. Contributes ctx.postgres — an RLS-scoped pg client, the safe version of "authenticate, then query as the user". This is the direct-connection counterpart to withSupabaseClient, and its service-role companion is withPostgresAdminClient (@supabase/server/middleware/postgres-admin).
Every query runs in its own short transaction that injects the caller's claims and drops to their role, exactly like PostgREST:
begin;
select set_config('request.jwt.claims', $claims, true); -- auth.uid() resolves
set local role "authenticated"; -- RLS now enforces
<your query>
commit;
Everything is transaction-local, so nothing leaks onto the pooled connection.
Only authenticated and anon are assumed. A token naming any other role — including service_role — is refused with a 500 and code: 'UNSUPPORTED_ROLE', never silently downgraded to anon: running the query as the wrong identity would return zero rows and leave nothing to debug. Bypassing RLS is a separate, explicit opt-in: compose withPostgresAdminClient.
Custom roles. Supabase supports custom Postgres roles via the
roleclaim, and RLS still applies to them. They are not supported here yet, so such a token is refused rather than downgraded.
Reads the caller's claims from ctx.jwtClaims, which withSupabase already populates (JWKS-verified) — so inside withSupabase you compose it directly:
withSupabase({ auth: 'user', middleware: [withPostgresClient()] }, handler)
Standalone (no withSupabase), pair it with withClaims so ctx.jwtClaims is present before it runs.
Table grants. Queries run as
authenticatedoranon, so those roles need explicit table privileges (e.g.grant select, insert on <table> to authenticated) in addition to RLS policies. A missing grant fails withpermission denied(SQLSTATE 42501) before RLS is consulted.
Runtime note.
pgneeds raw TCP, so this runs on Node/Deno (including the Supabase Edge runtime), not on Workers-style isolates.
The composable middleware surface tracks @supabase/middleware 0.x — entry shapes, context keys, and config options may change between 0.x releases.