← All posts
·updated ·12 min read·GuardLayer·how we write

How to test Supabase RLS policies (SQL, pgTAP, SDK)

#supabase#rls#testing#pgtap#next.js

To test Supabase RLS, run your queries as the role a real request uses: authenticated with a user's JWT claims, or anon. The SQL Editor runs as postgres by default, which bypasses RLS, so a broken policy looks exactly like a working one there. Impersonate a user with set local role and request.jwt.claims inside begin; ... rollback;, turn those checks into pgTAP tests that supabase test db runs locally and in CI, and add one supabase-js test where user A tries to read user B's rows.

RLS fails silently. A wrong policy doesn't throw. It returns the wrong rows, and you find out when someone reads data that isn't theirs. If you're still getting the model straight (grants vs policies, USING vs WITH CHECK), start with the complete guide to Supabase Row Level Security. This post is about proving your policies do what you think.

How do I test RLS policies in Supabase?

You test RLS by running the same query as two different users and as an anonymous caller, then asserting what each one gets back. There are four levels, from quickest to most complete:

  1. Studio's role selector. Pick a role or a user in the SQL Editor and run a query. Good for a quick look.
  2. Plain SQL impersonation. set local role plus request.jwt.claims in a transaction. Works in the SQL Editor and in psql.
  3. pgTAP tests. The same impersonation, written as assertions in supabase/tests/ and run with supabase test db.
  4. supabase-js tests. Real users signed in through Supabase Auth, hitting the Data API the way your app does.

Levels 3 and 4 are the ones that keep working after the next migration. The rest of this post builds each one against a small notes table.

Why the SQL Editor shows every row

The SQL Editor connects as postgres. That role owns the tables you create and has the BYPASSRLS attribute, which Supabase's RLS docs point out when explaining why definer functions skip policies. So every query you run there ignores your policies. A using (true) policy and a correct one return the same rows.

Studio has a fix for this. The SQL Editor toolbar has a Role button that shows postgres by default. It opens a "Run SQL query as a role" menu with three options: postgres (labelled Superuser), Anonymous (not logged in) and Authenticated (logged-in user), where you can pick a real user from your project. Under the hood, Studio's source prepends set_config('role', ...) and set_config('request.jwt.claims', ...) to your query. That's the same thing you can write yourself.

Impersonate a user in plain SQL

PostgREST switches to the request's role and exposes the JWT as the request.jwt.claims setting. auth.uid() reads it. Here is its definition from the Supabase Auth migrations:

create or replace function auth.uid()
returns uuid
language sql stable
as $$
  select
  coalesce(
    nullif(current_setting('request.jwt.claim.sub', true), ''),
    (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')
  )::uuid
$$;

It checks the old per-claim setting request.jwt.claim.sub first, then the sub key of the JSON in request.jwt.claims. Either works in a test. The JSON form matches what PostgREST and Studio set today, and it also feeds auth.jwt().

So to see what one user sees, paste this into the SQL Editor (with the Role button left on postgres) or psql:

begin;

set local role authenticated;
set local request.jwt.claims = '{"sub":"11111111-1111-1111-1111-111111111111","role":"authenticated"}';

select auth.uid();           -- the uuid above
select * from public.notes;  -- only that user's rows

-- Now act as an anonymous caller. Clear the claims too,
-- or auth.uid() still returns the user above.
set local role anon;
set local request.jwt.claims = '{"role":"anon"}';

select auth.uid();           -- null
select * from public.notes;  -- nothing (or an error, see below)

rollback;

set local only lasts until the end of the transaction, and rollback throws away anything you changed. The comment in the middle matters. Switching the role does not clear the claims, so if you skip that line, your "anon" check still runs with a user id and can pass for the wrong reason. If auth.uid() comes back null when it shouldn't, see why auth.uid() returns null in RLS.

Write pgTAP tests with supabase test db

Supabase's CLI runs pgTAP tests against your local database. supabase test new notes_rls scaffolds a test file, supabase test db runs everything under supabase/tests/ with pg_prove (per the CLI reference), and the testing guide keeps database tests in supabase/tests/database/. Start the stack with supabase start first.

Here is the migration the tests target. It's the correct version of the policy in the sample at the bottom of this post:

create table public.notes (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null,
  body text
);

alter table public.notes enable row level security;

grant select, insert, update, delete on public.notes to authenticated;

create policy "users read their own notes"
  on public.notes for select
  to authenticated
  using ((select auth.uid()) = user_id);

create policy "users write their own notes"
  on public.notes for insert
  to authenticated
  with check ((select auth.uid()) = user_id);

The explicit grant is there because, since October 30, 2026, Supabase no longer grants the API roles access to new public tables automatically (discussion #45329, and our write-up of the Data API change). anon gets no grant on purpose.

Now supabase/tests/database/notes_rls.test.sql:

begin;
select plan(5);

-- Setup runs as postgres, so these inserts skip RLS.
insert into public.notes (user_id, body) values
  ('11111111-1111-1111-1111-111111111111', 'alice note'),
  ('22222222-2222-2222-2222-222222222222', 'bob note');

-- Act as Alice.
set local role authenticated;
set local request.jwt.claims = '{"sub":"11111111-1111-1111-1111-111111111111","role":"authenticated"}';

select is(
  (select count(*)::int from public.notes),
  1,
  'Alice sees only her own note'
);

select is_empty(
  $$ select 1 from public.notes where user_id = '22222222-2222-2222-2222-222222222222' $$,
  'Alice cannot read Bob''s note'
);

select throws_ok(
  $$ insert into public.notes (user_id, body) values ('22222222-2222-2222-2222-222222222222', 'forged') $$,
  '42501',
  'new row violates row-level security policy for table "notes"',
  'Alice cannot insert a note as Bob'
);

select lives_ok(
  $$ insert into public.notes (user_id, body) values ('11111111-1111-1111-1111-111111111111', 'mine') $$,
  'Alice can insert her own note'
);

-- Act as an anonymous caller: new role, no user.
set local role anon;
set local request.jwt.claims = '{"role":"anon"}';

select throws_ok(
  $$ select * from public.notes $$,
  '42501',
  'permission denied for table notes',
  'anon has no access to notes at all'
);

select * from finish();
rollback;

Run it with supabase test db. Note the two different 42501 errors. The insert as Bob is stopped by RLS. The anon read is stopped one step earlier, by the missing grant. If your project still gives anon a grant on this table, the last assertion fails. Then either revoke it or assert is_empty instead, which proves RLS filters every row.

Two habits make these tests trustworthy. First, test the negative cases (cross-user reads, forged inserts), not only "Alice sees her row". Second, check that the suite can fail: Supabase's guide to testing RLS suggests temporarily adding a using (true) policy and confirming a test goes red.

Real test users with supabase_test_helpers

Hardcoded UUIDs stop working once user_id references auth.users, because the users have to exist. The community supabase_test_helpers extension from Basejump handles that. Supabase's advanced pgTAP guide installs it with dbdev:

select dbdev.install('basejump-supabase_test_helpers');

Then in your tests:

begin;
create extension if not exists "basejump-supabase_test_helpers";
select plan(3);

select tests.rls_enabled('public', 'notes');  -- fails if RLS is off on notes

select tests.create_supabase_user('alice');
select tests.create_supabase_user('bob');

insert into public.notes (user_id, body)
values (tests.get_supabase_uid('bob'), 'bob note');

select tests.authenticate_as('alice');
select is_empty(
  $$ select 1 from public.notes $$,
  'Alice cannot see Bob''s note'
);

select tests.clear_authentication();  -- back to anon, claims cleared
select throws_ok(
  $$ select * from public.notes $$,
  '42501',
  'permission denied for table notes',
  'anon cannot read notes'
);

select * from finish();
rollback;

tests.authenticate_as sets the role to authenticated and writes the user's sub, email and metadata into request.jwt.claims. tests.clear_authentication switches to anon and clears the claims, so it avoids the leftover-claims trap above. tests.authenticate_as_service_role() is there for setup that needs to skip RLS. Keep the extension in your test database only, as its README advises.

RLS failure or missing GRANT?

When a test against a new table fails with 42501, read the message before you touch a policy. The grant check runs before RLS, so the two look alike but need opposite fixes:

What you seeWhat it meansRead next
permission denied for table notesThe role has no table privilege. No policy ran.permission denied for table
new row violates row-level security policy for table "notes"The grant is fine. A WITH CHECK rejected the row.new row violates RLS policy
[] with no errorThe grant is fine. USING filtered every row.select returns an empty array

That last row is why read tests should assert on rows, not on errors. A blocked select, update or delete never throws. It just touches zero rows.

Test cross-tenant reads with supabase-js

Database tests prove the policy logic. An SDK test proves the whole path: Supabase Auth issuing the JWT, the Data API, the grant and the policy together. This one uses Vitest against the local stack. The secret key is only used to create users; every assertion runs through a client signed in with the publishable (or legacy anon) key.

import { createClient } from "@supabase/supabase-js";
import { beforeAll, expect, test } from "vitest";

const url = process.env.SUPABASE_URL!;
const publishableKey = process.env.SUPABASE_PUBLISHABLE_KEY!; // or the legacy anon key
const admin = createClient(url, process.env.SUPABASE_SECRET_KEY!, {
  auth: { persistSession: false },
});

async function newUser(name: string) {
  const email = `${name}-${Date.now()}@example.test`;
  const password = crypto.randomUUID();
  const { data, error } = await admin.auth.admin.createUser({
    email,
    password,
    email_confirm: true,
  });
  if (error) throw error;

  const client = createClient(url, publishableKey, { auth: { persistSession: false } });
  const { error: signInError } = await client.auth.signInWithPassword({ email, password });
  if (signInError) throw signInError;
  return { id: data.user.id, client };
}

let alice: Awaited<ReturnType<typeof newUser>>;
let bob: Awaited<ReturnType<typeof newUser>>;
let bobNoteId: string;

beforeAll(async () => {
  alice = await newUser("alice");
  bob = await newUser("bob");
  const { data, error } = await bob.client
    .from("notes")
    .insert({ user_id: bob.id, body: "bob's note" })
    .select("id")
    .single();
  if (error) throw error;
  bobNoteId = data.id;
});

test("Alice cannot read Bob's note", async () => {
  const { data, error } = await alice.client.from("notes").select("*").eq("id", bobNoteId);
  expect(error).toBeNull();
  expect(data).toEqual([]);
});

test("Alice cannot write a note as Bob", async () => {
  const { error } = await alice.client.from("notes").insert({ user_id: bob.id, body: "forged" });
  expect(error?.message).toContain("violates row-level security policy");
});

Never point the assertions at a client built with the secret or service_role key. That key bypasses RLS, so the test passes no matter how broken the policy is. For multi-tenant apps, write the same test across tenants instead of users, as in multi-tenant RLS in Supabase.

Prove anon gets nothing with curl

The fastest test of all needs no code. Call the Data API with only the publishable key, which is what anyone who opens your site has:

curl "https://<project-ref>.supabase.co/rest/v1/notes?select=*" \
  -H "apikey: <publishable-or-anon-key>"

You want [] or a 42501 permission error. Rows mean anyone can read that table. Supabase's API keys guide says to send publishable and secret keys in the apikey header, not as a Bearer token.

Doing that for every table by hand gets old. Live check connects to your project read-only and lists which tables anon can read right now, plus views and functions that skip RLS. It complements your tests rather than replacing them: it sees what's exposed today, while your tests pin down what each user is allowed to see.

Run RLS tests in CI with GitHub Actions

Supabase's testing overview gives this workflow. Save it as .github/workflows/db-tests.yml:

name: Database Tests

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: supabase/setup-cli@v1
      - run: supabase start
      - run: supabase test db

supabase start applies your migrations to a fresh local database, so every pull request is tested against the schema it ships. The SDK tests can run in the same job after supabase start, against the local URL and keys.

The policy these tests should catch

Here is the bug this suite exists to catch. RLS is on and the policy name says "their notes", but the predicate never mentions the user:

create policy "Users read their notes"
  on public.notes for select
  using (true);

using (true) returns every row to every caller. In the SQL Editor as postgres it looks perfect. Run the pgTAP file above against it and "Alice sees only her own note" fails with 2 rows instead of 1. A static scan catches it even before you write the test. Here is GuardLayer on that migration, live engine output:

guardlayer scan · supabase/migrations/0002_notes_policy.sqlLive engine output
Passed with warnings
92/100 · A
  • Warningsupabase/migrations/0002_notes_policy.sql:10

    Overly permissive RLS policy

    Scope the policy to the requesting user, e.g. USING (auth.uid() = user_id). Reserve (true) for genuinely public, read-only data.

The finding is the true predicate on a table that holds per-user data. A scanner and a test suite cover different ground: the scan flags a wide-open policy on the push that adds it, and the tests prove the policies you did scope behave under real roles.

FAQ

Why does my RLS policy work in the SQL Editor but leak in the app? Because the SQL Editor runs as postgres by default, and that role bypasses RLS. Your policy never ran. Switch the editor's Role button to Authenticated and pick a user, or wrap your query in begin; set local role authenticated; set local request.jwt.claims = '...'; ... rollback;.

How do I impersonate a user in Supabase? In Studio, use the Role button in the SQL Editor (or Table Editor) and choose Authenticated plus a user. In SQL, run set local role authenticated and set request.jwt.claims to a JSON object with that user's sub inside a transaction. In pgTAP, tests.authenticate_as('alice') from supabase_test_helpers does both.

How do I set auth.uid() in a test? Set the claims for the transaction: set local request.jwt.claims = '{"sub":"<uuid>","role":"authenticated"}';. auth.uid() reads sub from that JSON (or from the older request.jwt.claim.sub setting). When you switch to anon afterwards, reset the claims too.

How do I run Supabase RLS tests in CI? Put pgTAP files under supabase/tests/database/, then in GitHub Actions use supabase/setup-cli@v1, run supabase start, then supabase test db. Each test runs inside begin/rollback, so nothing persists between runs.

Can I test RLS with the service_role or secret key? Not for assertions. Those keys bypass RLS, so a broken policy still passes. Use them only to create test users and seed data, and assert through a client signed in as a real user with the publishable or anon key.

My test fails with 42501. Is my policy wrong? Check the message. permission denied for table means a missing GRANT, which is common on tables created after October 30, 2026. new row violates row-level security policy means a WITH CHECK rejected the row. Only the second is about your policy.

live check · read-only

See which of your Supabase tables anyone can read, free

Connect your Supabase project read-only. GuardLayer checks RLS, policies, grants and functions as they are right now, and gives you the SQL to fix each problem. It never reads your rows and can't change anything.

Check my Supabase project

Prefer to check code instead? Scan your repo, no signup.

Keep reading