Fix “infinite recursion detected in policy for relation” in Supabase

Updated

Error messageinfinite recursion detected in policy for relation "team_members" (42P17)

A policy on a table reads that same table, or two tables’ policies read each other, so checking access triggers the check again. Move the membership lookup into a security definer function with a fixed search_path and call it from the policy. The function runs as its owner, so the inner query doesn’t re-run the policy.

What the broken policy looks like

This shows up the moment an app gets teams or workspaces. A typical generated policy:

create policy "Members see their team" on team_members
for select using (
  team_id in (
    select team_id from team_members where user_id = auth.uid()
  )
);

To answer “which rows of team_members can I see”, Postgres must read team_members, which asks the same policy again. It fails every query that touches the table, including joins from other tables.

The fix: a security definer function

create or replace function public.my_team_ids()
returns setof uuid
language sql
stable
security definer
set search_path = ''
as $$
  select team_id
  from public.team_members
  where user_id = (select auth.uid());
$$;

drop policy "Members see their team" on public.team_members;

create policy "Members see their team" on public.team_members
for select to authenticated
using (team_id in (select public.my_team_ids()));
  • security definer makes the function run as its owner, which bypasses RLS inside it.
  • set search_path = '' and fully qualified names stop a caller from swapping in their own tables.
  • Functions in public are callable through the API. This one only returns the caller’s own teams, which is safe. Anything that returns other users’ data belongs in a schema the API doesn’t expose.

Check that it worked

As a member, select from team_members: you see only your teams. As a user from another team, you see none of them. Add an index on team_members(user_id), since the function runs on every query.

Sources