Database / Supabase Intermediate to Advanced Interview Questions
How does a custom access token Auth Hook let you enrich a user's JWT with custom claims?
Supabase Auth calls a designated hook function (implemented as a Postgres function or an Edge Function) at the moment it's about to issue a new access token, passing in the current claims it was going to include. The hook function can inspect the user, run its own queries, and return a modified claims object that Auth then uses to actually sign the token.
create function custom_access_token_hook(event jsonb) returns jsonb as $$ declare claims jsonb; org_id uuid; begin select organization_id into org_id from profiles where id = (event->>'user_id')::uuid; claims := event->'claims'; claims := jsonb_set(claims, '{organization_id}', to_jsonb(org_id)); return jsonb_set(event, '{claims}', claims); end; $$ language plpgsql stable;
Because this runs once at token-issuance time rather than on every request, the resulting organization_id claim is then available inside every Row Level Security policy for the lifetime of that token without an extra database lookup per query — a meaningful performance win for policies that would otherwise need a join back to a profile table on every single row check.
More Related questions...