rls-policies.sql

From the guide Supabase authentication in TypeScript: two safe ways, with code. Placeholder values only: put your own keys in environment variables, never in the code.

rls-policies.sqlSQLRawExternal
-- rls-policies.sql: with Supabase Auth, the browser queries tables itself, so RLS policies are the lock.
-- Each row belongs to one user (user_id). A signed-in user reads and changes only their own rows; anon gets nothing.
create table public.notes (
  id         bigint generated always as identity primary key,
  user_id    uuid not null default auth.uid() references auth.users (id) on delete cascade,
  body       text not null,
  created_at timestamptz not null default now()
);
create index notes_user_id_idx on public.notes (user_id);   -- policies filter on it: index it

alter table public.notes enable row level security;

-- Grants decide whether a role may run an operation on the table at all; policies then pick the rows. Not every project
-- grants these by default, and a missing grant fails with error 42501 before any policy runs.
-- (https://supabase.com/docs/guides/database/postgres/row-level-security, read 2026-11-22)
revoke all on public.notes from anon;
grant select, insert, update, delete on public.notes to authenticated;

-- (select auth.uid()) instead of auth.uid(): Postgres runs it once per query, not once per row.
create policy "Users read their own notes" on public.notes
  for select to authenticated using ((select auth.uid()) = user_id);

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

create policy "Users change their own notes" on public.notes
  for update to authenticated using ((select auth.uid()) = user_id) with check ((select auth.uid()) = user_id);

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

Back to the guide