# Supabase RLS for Mobile Apps: Your Anon Key Is Public, So Your Policies Are Your Security

*Why row level security is the only thing standing between your users' data and anyone with a copy of your app, the policy patterns that hold up, the eight mistakes we see most, and how to test it all before launch.*

**i**n an Expo + Supabase app, the Supabase URL and anon (publishable) key ship inside the app bundle. Anyone can extract them and query your database directly, without your app. Row level security (RLS) is what decides what those queries can see and change. Enable it on every table, write policies around `auth.uid()`, never authorize with `user_metadata`, watch out for views and `security definer` functions, and test policies as a real user before you ship.

If you've built a mobile app on Supabase, there's a moment worth having before your users have it for you: realizing that your app isn't the only client of your database. Your API is public. The app is just one way to call it.

## Why mobile apps make RLS non-negotiable

Supabase's client talks to your database through an auto-generated REST API. To do that from a phone, the app needs two things: your project URL and the anon (publishable) key. Both are compiled into your app.

That's by design, and it's fine, **as long as RLS is doing its job.** Here's what anyone can do with an app they downloaded:

1. Extract the bundle (React Native JavaScript bundles are readable with ordinary tools).
2. Find the Supabase URL and key.
3. Call your API directly:

```bash
curl "https://YOUR-PROJECT.supabase.co/rest/v1/projects?select=*" \
  -H "apikey: YOUR-ANON-KEY" \
  -H "Authorization: Bearer YOUR-ANON-KEY"
```

If that request returns rows, your data is public, no matter what your app's screens show. Hiding a button in the UI is not security. The only thing that decides the answer to that request is your RLS policies.

Two consequences follow:

- **The anon key isn't a secret, and rotating it doesn't fix a missing policy.**
- **The service role key bypasses RLS entirely,** so it must never be in the app. Keep it on the server, in Edge Functions or your backend.

## Step 1: Enable RLS on every table, every time

With RLS enabled and no policies, Postgres denies everything to the `anon` and `authenticated` roles. That's the safe starting point.

```sql
alter table public.projects enable row level security;
```

Tables created in the Supabase dashboard's table editor typically have RLS turned on, but tables created with SQL migrations don't get it automatically. Put `enable row level security` in the same migration that creates the table, so a new table can never ship without it.

Check for stragglers with the dashboard's Security Advisor, or with a query:

```sql
select schemaname, tablename
from pg_tables
where schemaname = 'public' and rowsecurity = false;
```

## Step 2: The core pattern: rows owned by a user

Most mobile app data belongs to one user: their projects, notes, orders. Give each table a `user_id` and write one policy per operation:

```sql
create table public.projects (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users (id) on delete cascade default auth.uid(),
  name text not null,
  created_at timestamptz not null default now()
);

alter table public.projects enable row level security;

create index projects_user_id_idx on public.projects (user_id);

create policy "Read own projects"
  on public.projects for select to authenticated
  using ( (select auth.uid()) = user_id );

create policy "Create own projects"
  on public.projects for insert to authenticated
  with check ( (select auth.uid()) = user_id );

create policy "Update own projects"
  on public.projects for update to authenticated
  using ( (select auth.uid()) = user_id )
  with check ( (select auth.uid()) = user_id );

create policy "Delete own projects"
  on public.projects for delete to authenticated
  using ( (select auth.uid()) = user_id );
```

The details matter:

- `using` filters which existing rows a user can see or touch. `with check` validates the new version of a row being written. Inserts need `with check`; updates should have both, so a user can't change `user_id` to move a row into someone else's account.
- `to authenticated` keeps signed-out (`anon`) requests out entirely.
- `(select auth.uid())` instead of bare `auth.uid()` lets Postgres evaluate it once per query instead of once per row, which Supabase recommends for performance.
- **The index on** `user_id` matters more than it looks. Every policy check filters on that column; without an index, large tables get slow fast.
- `default auth.uid()` on `user_id` means the app doesn't even need to send it, and the `with check` rejects anyone who tries to send someone else's.

## Step 3: Shared data: teams and memberships

Once users share data (teams, workspaces, families), policies check membership instead of ownership. The trap here is recursion: if the policy on `team_members` queries `team_members`, Postgres can end up evaluating the policy inside itself and fail with an "infinite recursion" error.

The usual fix is a small `security definer` helper that checks membership without triggering RLS again:

```sql
create or replace function public.is_team_member(p_team_id uuid)
returns boolean
language sql
security definer
set search_path = ''
stable
as $$
  select exists (
    select 1 from public.team_members
    where team_id = p_team_id
      and user_id = (select auth.uid())
  );
$$;

create policy "Members read team projects"
  on public.team_projects for select to authenticated
  using ( public.is_team_member(team_id) );
```

Because `security definer` functions bypass RLS, keep them tiny, always set `search_path = ''` and fully qualify table names, and make sure they only ever answer a question about the **current** user.

## The eight RLS mistakes we see most

### 1\. A table without RLS

The most common and most serious. One new table added in a hurry, often for a feature that "doesn't hold anything sensitive", and it's readable and writable by anyone with the anon key.

### 2\. `using (true)` on data that isn't public

`using (true)` means "everyone can see every row". It's correct for genuinely public data, like a list of countries or published blog posts. It's a leak on anything else. Search your migrations for it and justify each one.

### 3\. Authorizing with `user_metadata`

```sql
-- Don't do this
using ( (auth.jwt() -> 'user_metadata' ->> 'role') = 'admin' )
```

Users can update their own `user_metadata` from the client. If a policy trusts it, any user can make themselves an admin. Use `app_metadata` (which only the service role can change) or, better, a roles table in your database that users can't write to.

### 4\. Forgetting that RLS is per row, not per column

If a user can update their `profiles` row, they can update **every column** in it, including `plan`, `is_verified` or `credits`. RLS can't stop that by itself. Move privileged fields to a table users can't write to, use column-level privileges, or validate changes with a trigger.

### 5\. Views that bypass RLS

By default, a Postgres view runs with the permissions of the user who created it, which in Supabase is usually a role that bypasses RLS. A view over `projects` can quietly expose every row. On Postgres 15 and later, create views with `security_invoker` so the caller's policies apply:

```sql
create view public.project_summaries
with (security_invoker = true)
as select id, name, created_at from public.projects;
```

### 6\. RPC functions with `security definer`

A `security definer` function you call with `supabase.rpc()` runs with elevated privileges and ignores RLS. If it takes a `user_id` argument and trusts it, anyone can pass someone else's. Inside such functions, use `auth.uid()` instead of trusting arguments, and revoke execute from roles that shouldn't call it:

```sql
revoke execute on function public.admin_report() from anon, authenticated;
```

### 7\. Storage with no folder policies

Files in Supabase Storage are protected by policies on `storage.objects`, separate from your tables. A common, safe pattern for user uploads is a folder per user:

```sql
create policy "Users manage own files"
  on storage.objects for all to authenticated
  using (
    bucket_id = 'uploads'
    and (storage.foldername(name))[1] = (select auth.uid())::text
  )
  with check (
    bucket_id = 'uploads'
    and (storage.foldername(name))[1] = (select auth.uid())::text
  );
```

The app then uploads to `userId/filename`. Remember that a **public** bucket serves any file to anyone with its URL, regardless of these policies, so keep private files in private buckets and use signed URLs.

### 8\. Using the service role key to "fix" a permission error

When a query fails because of RLS, the tempting fix is to use the service role key. In a mobile app, that hands full database access to everyone who downloads it. If the app legitimately needs to do something RLS forbids, do it in an Edge Function that checks the user's identity first, and keep the key there.

## If AI wrote your schema, review the policies line by line

AI coding tools and app builders are great at generating Supabase schemas, and they're also where many of the mistakes above come from: a permissive `using (true)` added to make an error go away, a missing `with check`, or a new table without RLS because the prompt was about a feature, not security.

Treat generated SQL like a pull request from a fast new teammate:

1. List every table and confirm RLS is enabled.
2. Read every policy and say out loud who it lets do what.
3. Search for `using (true)`, `user_metadata`, `security definer` and views.
4. Run the tests below as two different users.

## How to test RLS before your users do

### Test as a user in SQL

You can impersonate a user inside a transaction and see exactly what they'd see:

```sql
begin;
set local role authenticated;
set local request.jwt.claims to '{"sub":"USER-A-UUID","role":"authenticated"}';

select count(*) from public.projects;          -- only user A's projects
update public.projects set name = 'hacked'
  where user_id = 'USER-B-UUID';               -- should update 0 rows

rollback;
```

The Supabase dashboard's SQL editor can also run queries as a chosen role or user, which is handy for quick checks.

### Test as an attacker with the anon key

Run the `curl` request from the start of this article against every table, signed out. Then sign in as one test user, take their access token, and try to read and modify another test user's rows. Every attempt should come back empty or rejected.

### Automate it

Policies regress when someone adds a table or "temporarily" loosens a rule. Write the checks as database tests (the Supabase CLI runs pgTAP tests with `supabase test db`) and run them in CI, so a leaky policy fails the build instead of reaching production.

## A pre-launch RLS checklist

1. RLS enabled on every table in exposed schemas.
2. Policies for select, insert, update and delete, with `with check` on writes.
3. No `using (true)` on private data.
4. No authorization based on `user_metadata`.
5. Privileged columns protected from user updates.
6. Views use `security_invoker`; `security definer` functions are minimal and locked down.
7. Storage buckets private where needed, with folder policies.
8. Service role key only on the server.
9. Indexes on every column your policies filter by.
10. Policy tests passing, for two users and for signed-out requests.

## FAQ

**Is it safe to put the Supabase anon key in a mobile app?** Yes, as long as RLS is enabled with correct policies on every exposed table. The key only grants what your policies allow.

**Does RLS slow down queries?** Policies add filters to every query. With `(select auth.uid())` and indexes on the columns your policies use, the overhead is usually small.

**Does RLS apply to Realtime?** Postgres Changes subscriptions respect RLS for authenticated users, so users only receive changes to rows they can see.

**Can I skip RLS if all data access goes through my own backend?** Only if the database is never reachable with the anon key. If your mobile app talks to Supabase directly, RLS is required.

## Conclusion

In a mobile app, you ship your database's front door key to every user. That's normal, and it's safe, because RLS is the lock. Enable it everywhere, write policies around `auth.uid()`, avoid the eight mistakes above and test as a real user and as an attacker before you launch.

*Have you found an RLS gap in your own app, or in generated code? Share what it was in the comments, so others can check for it too.*
