VibeCPR

← All fixes

Supabase · RLS · Policies

Fix Supabase "infinite recursion detected in policy for relation" (42P17) in RLS

Updated · Applies to: Supabase, Lovable, Bolt, Cursor, v0, Replit, Claude Code

TL;DR fix: A policy on profiles that checks exists (select 1 from profiles where id = auth.uid() and role = 'admin') reads the table it protects, so Postgres has to apply the same policy again, forever, and stops with 42P17 infinite recursion detected in policy for relation "profiles". The same happens when teams checks team_members and team_members checks teams. Fix: move the lookup into a security definer function with set search_path = '' in a private schema the API doesn't expose, revoke EXECUTE from public, grant it to authenticated only, and call it as (select private.is_admin()) in the policy. Alternatives: read a role claim from the JWT, or make one side of a two-table loop one-way.

Steps

  1. Find the policy that reads its own table (or a table that reads it back). Run the loop-finder query below in the Supabase SQL editor. Every row marked LOOP is a policy that makes Postgres re-apply RLS on a table it is already applying RLS to.
  2. Create a private schema for helpers. create schema if not exists private; Don't add it to Exposed schemas in your API settings, so the helper can't be called at /rest/v1/rpc.
  3. Move the lookup into a security definer function. Write an argument-free function such as private.is_admin() or private.my_team_ids() that reads the table with (select auth.uid()). Mark it security definer and set search_path = '', and schema-qualify every table name inside it.
  4. Lock down who can run it. In one transaction: revoke execute on the function from public, then grant usage on schema private and execute on the function to authenticated only. Never leave it callable by anon.
  5. Rewrite the policy to call the helper, wrapped in select. Replace the subquery with (select private.is_admin()) or team_id in (select private.my_team_ids()). Wrapping makes Postgres run it once per query instead of once per row.
  6. Retest as an admin, a member, an outsider and anon. Run the same query as each kind of user. The error should be gone, each user should see only their rows, and anon should get permission denied when calling the helper.

What the error looks like

In the browser console or your Supabase logs:

{ "code": "42P17", "message": "infinite recursion detected in policy for relation \"profiles\"" }

PostgREST returns it as HTTP 500, so your app usually shows an empty list, a spinner or “something went wrong” on every page that reads that table. It typically starts right after you (or your agent) added an “admins can see everything” or “members can see their team” policy.

Why it happens

A policy is a filter Postgres adds to every query on the table. If the filter itself reads the same table, Postgres has to add the filter to that read too, and so on forever. It detects this and refuses with 42P17 instead. Two shapes cause almost every case we see in Lovable, Bolt and Cursor apps:

1. A policy that reads its own table. The admin check:

-- profiles policy that reads profiles: 42P17 on every select
create policy "admins read all profiles" on public.profiles for select to authenticated
  using (exists (select 1 from public.profiles p
                 where p.id = (select auth.uid()) and p.role = 'admin'));

-- team_members policy that reads team_members ("see my teammates"): 42P17
create policy "see teammates" on public.team_members for select to authenticated
  using (team_id in (select tm.team_id from public.team_members tm
                     where tm.user_id = (select auth.uid())));

2. Two tables whose policies read each other. Supabase’s own docs use this sharing example: teams (or lists) checks team_members to find members, and team_members checks teams to find the owner. Each read triggers the other table’s policy, which reads the first table again.

Things we confirmed on Postgres 17 (details in what we verified):

  • It fails for everyone the policy applies to, admins included. A policy with no to clause applies to anon too, so signed-out visitors hit the error as well.
  • An UPDATE policy, or an INSERT ... with check that reads the same table (“only team admins can add members”), fails the same way. The insert case only needs the table to have any SELECT policy, even a simple user_id = auth.uid() one.
  • Wrapping the subquery in (select ...) does not fix it.

Step 1: the 2-minute check

Paste this into the Supabase SQL editor. It lists every policy in public that reads an RLS-protected table, and flags the loops:

with pol as (
  select tablename, policyname, cmd,
         coalesce(qual, '') || ' ' || coalesce(with_check, '') as expr
  from pg_policies where schemaname = 'public'
), reads as (
  select pol.tablename, pol.policyname, pol.cmd, c.relname as reads_table
  from pol
  join pg_class c on c.relnamespace = 'public'::regnamespace
   and c.relkind in ('r', 'p') and c.relrowsecurity
   and pol.expr ~* ('(from|join)\s+(public\.)?"?' || c.relname || '"?\M')
)
select r.tablename, r.policyname, r.cmd, r.reads_table,
  case when r.reads_table = r.tablename then 'LOOP: reads its own table'
       when exists (select 1 from reads r2
                    where r2.tablename = r.reads_table and r2.reads_table = r.tablename)
         then 'LOOP: ' || r.reads_table || ' reads ' || r.tablename || ' back'
       else 'ok (one-way)' end as verdict
from reads r order by 1, 2;

On our broken test schema it found all four policies:

  tablename   |        policyname        | reads_table  | verdict
 profiles     | admins read all profiles | profiles     | LOOP: reads its own table
 team_members | owners read membership   | teams        | LOOP: teams reads team_members back
 team_members | see teammates            | team_members | LOOP: reads its own table
 teams        | members read teams       | team_members | LOOP: team_members reads teams back

It’s a text match, so it misses loops that go through a view or a function that reads the table with the caller’s rights (security invoker). Longer chains (A reads B reads C reads A) show up as several one-way rows; follow them by hand.

What you seeCauseFix
42P17 on profiles after adding an admin policyPolicy reads profiles to check the roleFix A or Fix B
42P17 on team_members / members“See my teammates” policy reads the same tableFix A
42P17 on teams and team_membersTwo policies read each otherFix C or Fix A
42P17 only when inserting memberswith check reads the same tableFix A (private.my_admin_team_ids())
stack depth limit exceeded (54001) after adding a helperHelper’s owner doesn’t bypass RLSOwner caveat
Error gone, but anon can call /rest/v1/rpc/get_user_roleHelper in public with default grantsSecurity caveats
new row violates row-level security policy (42501)Different error: no policy allows the insertThat fix

Fix A: a security definer helper in a private schema

This is the fix in Supabase’s docs. The helper reads the table as its owner. On Supabase that’s postgres, which has BYPASSRLS, so the inner read doesn’t run the policy again and the loop is broken. The function filters on auth.uid() itself, so it only ever answers for the caller.

create schema if not exists private;   -- do NOT add it to "Exposed schemas"

begin;
create function private.is_admin() returns boolean
language sql stable security definer set search_path = '' as $$
  select exists (select 1 from public.profiles
                 where id = (select auth.uid()) and role = 'admin')
$$;

create function private.my_team_ids() returns setof int   -- use uuid if your ids are uuids
language sql stable security definer set search_path = '' as $$
  select team_id from public.team_members where user_id = (select auth.uid())
$$;

create function private.my_admin_team_ids() returns setof int
language sql stable security definer set search_path = '' as $$
  select team_id from public.team_members
  where user_id = (select auth.uid()) and role = 'admin'
$$;

revoke execute on function private.is_admin(), private.my_team_ids(),
  private.my_admin_team_ids() from public;
grant usage on schema private to authenticated;
grant execute on function private.is_admin(), private.my_team_ids(),
  private.my_admin_team_ids() to authenticated;
commit;

Then replace the looping policies:

drop policy "admins read all profiles" on public.profiles;
drop policy "see teammates" on public.team_members;

create policy "own profile" on public.profiles for select to authenticated
  using (id = (select auth.uid()));
create policy "admins read all profiles" on public.profiles for select to authenticated
  using ((select private.is_admin()));

create policy "see teammates" on public.team_members for select to authenticated
  using (team_id in (select private.my_team_ids()));
create policy "team admins add members" on public.team_members for insert to authenticated
  with check (team_id in (select private.my_admin_team_ids()));

create policy "members read teams" on public.teams for select to authenticated
  using (id in (select private.my_team_ids()));
create policy "owners read teams" on public.teams for select to authenticated
  using (owner_id = (select auth.uid()));

In our test: the admin saw all 3 profiles and the two members saw 1 each. Bob saw both rows of his team and none of Carol’s. The team admin could add a member, and a plain member got 42501. anon got permission denied for schema private when calling the helpers, and the loop finder came back empty.

Why each piece matters:

  • set search_path = '' (and public. on every table): Postgres’s docs warn that a security definer function with an open search path can be tricked into running someone else’s objects with the owner’s rights.
  • revoke ... from public: Postgres grants EXECUTE on every new function to PUBLIC. Revoking only from anon leaves that grant in place.
  • grant ... to authenticated: policies run with the caller’s rights, so the caller needs EXECUTE and USAGE on the schema. If you revoke from authenticated too, the policy itself fails with permission denied for function.
  • (select ...) around the call: Supabase’s performance guide says wrapping makes Postgres run it once and reuse the result (an initPlan). In our 50,000-row test the unwrapped private.is_admin() ran 50,000 times (396 ms); wrapped, it ran once (3 ms), with identical results. Only wrap calls that don’t take a column of the row as input.
  • No arguments: a helper like is_admin() that reads auth.uid() can only tell users about themselves. A helper that takes a user or team id lets anyone ask about anyone (see below).

Fix B: read the role from the JWT

If the check is “is this user an admin/moderator”, you can avoid reading a table at all. Supabase’s RBAC guide adds a user_role claim with a custom access token hook: a function Supabase Auth runs before it issues each token.

-- From Supabase's RBAC guide (trimmed): roles live in their own table
create table public.user_roles (
  id bigint generated by default as identity primary key,
  user_id uuid references auth.users on delete cascade not null,
  role text not null, unique (user_id, role));

create or replace function public.custom_access_token_hook(event jsonb)
returns jsonb language plpgsql stable as $$
declare claims jsonb; user_role text;
begin
  select role into user_role from public.user_roles where user_id = (event->>'user_id')::uuid;
  claims := event->'claims';
  if user_role is not null then claims := jsonb_set(claims, '{user_role}', to_jsonb(user_role));
  else claims := jsonb_set(claims, '{user_role}', 'null'); end if;
  return jsonb_set(event, '{claims}', claims);
end $$;

grant usage on schema public to supabase_auth_admin;
grant execute on function public.custom_access_token_hook to supabase_auth_admin;
revoke execute on function public.custom_access_token_hook from authenticated, anon, public;
grant all on table public.user_roles to supabase_auth_admin;
revoke all on table public.user_roles from authenticated, anon, public;
alter table public.user_roles enable row level security;
create policy "Allow auth admin to read user roles" on public.user_roles
  as permissive for select to supabase_auth_admin using (true);

Turn the hook on under Authentication → Hooks in the dashboard, then the policy is just:

create policy "admins read all profiles" on public.profiles for select to authenticated
  using ((select auth.jwt() ->> 'user_role') = 'admin');

Trade-offs, from the Supabase docs: the claim only changes when the user gets a new token, so a demoted admin keeps admin rights until their token refreshes (we reproduced that with an old token), and big claims make cookies bigger (some browsers cap a cookie at 4096 bytes). Use the hook for a small, slow-changing role, not for a long list of team ids. Never read roles from user_metadata: Supabase’s docs say users can update it themselves. app_metadata they can’t.

Fix C: make one side one-way

For a two-table loop, often only one direction is needed. Let team_members check only the caller’s own rows, and let teams read team_members:

drop policy "owners read membership" on public.team_members;
create policy "own membership rows" on public.team_members for select to authenticated
  using (user_id = (select auth.uid()));
-- "members read teams" on teams can keep its exists (select ... from team_members ...)

This needs no helper. The trade-off is that users now see only their own membership row, not their teammates. If owners or teammates need to read membership, read the other table through a Fix A helper instead of a direct subquery.

Security caveats: don’t trade a loop for a leak

A tempting shortcut (from you or your agent) is a helper in the public schema that takes an id, like public.get_user_role(uid uuid) or public.get_team_members(team_id). The recursion goes away, but:

  • anon can call it. Functions in public are callable at POST /rest/v1/rpc/<name>, and Supabase grants EXECUTE on new functions to anon and authenticated by default. In our test, the anon role (just your public key) learned that Alice is an admin and listed the members of another team. Supabase’s docs: never create a security definer function in an exposed schema.
  • Signed-in users can read other tenants. Bob could list team 2’s members through the helper while RLS showed him 0 rows of team 2.
  • Revoking from anon alone doesn’t help. The Postgres default PUBLIC grant still let anon run it. Revoke from public, anon.
  • It’s still in Security Advisor. Lints 0028/0029 flag security definer functions that anon or authenticated can execute.

For the full audit of every security definer function in your project and how to stop new ones getting the grant, see Fix a Supabase SECURITY DEFINER function anyone can call through /rest/v1/rpc.

Who owns the helper matters. Supabase’s docs say the helper “only skips RLS when its owner can”. In our tests:

  • A helper owned by a role without BYPASSRLS that the policy applies to failed with stack depth limit exceeded (54001).
  • If the policy doesn’t apply to that owner, the helper silently returns nothing (everyone sees 0 rows).
  • A helper owned by the table owner worked, until the table had FORCE ROW LEVEL SECURITY, then 54001 again.
  • A helper owned by a BYPASSRLS role, which is what postgres is on Supabase, kept working even with FORCE on.

So create helpers from the Supabase SQL editor (as postgres), and check the owner with select proname, pg_get_userbyid(proowner) from pg_proc where pronamespace = 'private'::regnamespace;.

Don’t “fix” it by turning RLS off or switching to using (true). Both make the table readable by anyone with your anon key. See Supabase RLS USING (true) makes your table public. And a helper that answers “is admin” is only as good as the column behind it: if users can edit their own role, see users who can update their own plan or is_admin column.

Paste this into Lovable, Bolt, Cursor or Claude Code

My Supabase app fails with "infinite recursion detected in policy for relation"
(42P17). Fix it without weakening security. Do not disable RLS, do not use
USING (true), and do not run anything until I approve the SQL.
1. List every RLS policy in the public schema whose USING or WITH CHECK reads
   its own table, or reads a table whose policy reads it back. Show the loop.
2. Move each lookup (is admin, my team ids, my admin team ids) into a function
   in a "private" schema (create it; it must NOT be in the API's exposed schemas):
   language sql stable security definer set search_path = '', no arguments,
   filtering on (select auth.uid()), every table name schema-qualified.
3. In one transaction: revoke execute on those functions from public; grant usage
   on schema private and execute on the functions to authenticated only.
4. Rewrite the policies to call them as (select private.fn()) or
   col in (select private.fn()), with "to authenticated" on every policy.
5. Do not create security definer functions in public, and none that take a
   user id or team id as an argument.
6. Give me SQL to test as an admin, a member, a non-member and anon: no 42P17,
   correct row counts, and anon gets "permission denied" calling the helpers.

What we verified

  • Tested locally (Nov 24, 2026, PostgreSQL 17.12 server on a throwaway local cluster, Supabase-style roles: anon/authenticated without BYPASSRLS, an owner role with BYPASSRLS playing Supabase’s postgres, auth.uid()/auth.jwt() written like Supabase’s, reading the request.jwt.claims setting PostgREST sets; research/rls-recursion-test/run.sh, output run.out.txt):
    • Reproduced 42P17 for an admin check on profiles (for the admin and for a member), with a policy without a to clause (anon too), with the check wrapped in (select ...), on an UPDATE policy, on a “see teammates” policy, on an INSERT with check reading the same table, and on a teams/team_members pair. With no SELECT policy on the table, that INSERT failed with 42501 instead of 42P17.
    • The loop-finder query flagged all four looping policies and returned nothing after Fix A.
    • Fix A: admin 3 profiles, members 1, anon 0. Bob saw his team’s 2 membership rows and none of team 2. The admin insert succeeded and the member insert got 42501. anon got permission denied for schema private; has_function_privilege showed anon false and authenticated true. With 50,000 rows, the wrapped helper ran once (3 ms) and the unwrapped one 50,000 times (396 ms).
    • Leak: public.get_user_role(uuid) and public.get_team_members(int) with Supabase-style default grants were callable by anon and leaked another team to Bob. Revoking from anon alone still leaked through PUBLIC; revoking from public, anon, authenticated blocked it and broke the policy that used it.
    • Fix B: the RBAC hook function, called as supabase_auth_admin, added user_role: "admin" for Alice and null for Bob. anon couldn’t run the hook and authenticated couldn’t read user_roles. The JWT-claim policy gave 3 vs 1 rows with no recursion. After Alice was demoted, a request with her old claims still saw 3 rows.
    • Fix C: one-way policies, no loop; Bob saw his team and only his own membership row.
    • Owner caveats: non-BYPASSRLS owner covered by the policy gave 54001; not covered gave 0 rows; table owner worked, then gave 54001 under FORCE RLS; BYPASSRLS owner worked under FORCE RLS.
  • Docs-based, not tested on a real Supabase project (sources below, all fetched Nov 24, 2026, HTTP 200; list in research/rls-recursion-2026-11-24.md): that postgres has BYPASSRLS on Supabase, the HTTP 500 status from PostgREST, /rest/v1/rpc exposure of public functions and the Exposed schemas setting, Supabase’s default EXECUTE grants to anon/authenticated, Security Advisor lints 0028/0029, enabling the access token hook under Authentication → Hooks, token refresh timing, the 4096-byte cookie note, and user_metadata being user-editable. We did not run supabase-js, PostgREST or Supabase Auth.
  • Our reading, not documented: which policy shapes Lovable, Bolt and Cursor generate most often.

Related: new row violates row-level security policy, SECURITY DEFINER functions callable by anon, USING (true) policies, users who can update their own plan or is_admin, “Sign in with Google” lets anyone in, and check your RLS in two minutes.

When to get help

Get help if your roles live in several tables, if your app has already shipped with the policy disabled "to make the error go away", or if Security Advisor flags security definer functions you didn't write.

FAQ

What does "infinite recursion detected in policy for relation" mean in Supabase?

An RLS policy on a table reads that same table, directly or through another table whose policy reads it back. To answer the query, Postgres must apply the policy, which needs the policy again, so it stops with error 42P17 instead. Supabase's docs say the query then fails for every role the policies apply to. Through the API it comes back as HTTP 500.

Why does my admin check on the profiles table cause infinite recursion?

A policy like exists (select 1 from profiles where id = auth.uid() and role = 'admin') on profiles asks Postgres to read profiles while it is deciding which profiles rows you may read. Move the lookup into a security definer function such as private.is_admin(), which reads profiles as its owner and skips RLS, and call it as (select private.is_admin()) in the policy.

Does wrapping the policy in (select ...) fix 42P17?

No. In our Postgres 17 test, wrapping the self-referencing subquery in select still raised 42P17. Wrapping is a speed fix: (select private.is_admin()) ran the helper once for a 50,000-row query instead of 50,000 times. Use it on top of the helper, not instead of it.

Is a SECURITY DEFINER helper function safe in an RLS policy?

Only if the API can't call it to read other people's data. Put it in a schema that isn't exposed (Supabase's docs use private), set search_path = '', revoke EXECUTE from public, grant it to authenticated only, and make it take no arguments and read auth.uid() itself. In our test, a public get_user_role(uid) helper told anon that Alice was an admin, and revoking only from anon didn't stop it, because of the default PUBLIC grant.

Can I put the user's role in the JWT instead?

Yes. A Supabase custom access token hook can add a claim like user_role, and the policy reads (select auth.jwt() ->> 'user_role') = 'admin' without touching any table, so it can't loop. The catch: the claim only changes when the user gets a new token. Never use user_metadata for roles, because users can edit it.

I fixed the recursion and now get "stack depth limit exceeded". Why?

Your helper's owner doesn't bypass RLS, so the helper runs the same policy again at run time. In our test that gave error 54001 instead of 42P17. On Supabase, create the helper in the SQL editor so it's owned by postgres, which has BYPASSRLS. A table owner without BYPASSRLS also fails once the table has FORCE ROW LEVEL SECURITY.

Should I just disable RLS to make the error go away?

No. With RLS off, anyone with your public anon key can read and write the whole table through the API, and a policy of using (true) is just as open for whoever it applies to. Both make the error go away by removing the protection. Fix the loop with a helper, a JWT claim or a one-way policy instead.

Sources

Related fixes