Anonymous access done deliberately
Public reads without public writes: design anonymous access on Supabase on purpose - filtered reads, scoped columns, abuse limits - instead of inheriting it.
Every Supabase app has anonymous users whether or not it wants them - anyone holding your public key counts. This article shows how to design what they can reach: published-only reads, scoped columns, capped queries - turning accidental openness into a decided interface.
Anonymous access gets designed in two ways: deliberately, as a product decision with filters and limits and documentation; or accidentally, as whatever was left reachable when development moved on. Both look identical from inside the app. From outside — where crawlers, competitors, researchers, and curious strangers live — the difference is the difference between a published catalog and an open database.
The pattern repeats across projects with almost comic regularity: an app gains public content (a storefront, a blog, listings), the tables carrying it get policies, and every other table keeps whatever state its creation left behind. Six months later, a scan finds support_tickets readable by anyone because it was created during a sprint where "enable RLS" wasn't yet muscle memory. Nothing malicious occurred; nobody decided anything. That's precisely the problem this article addresses: replacing non-decisions with decisions.
The good news: deliberate anonymous access is one of the cheapest security postures to implement well, because it's small. Anon needs almost nothing: usually read access to a handful of tables, filtered to published content, with writes closed entirely. The discipline is deciding exactly that list and proving it holds — which this article walks end to end, with runnable SQL throughout. Every statement was executed during preparation; every expected result was verified before being written here.
Anonymous is a design surface, not an oversight
Start by internalizing who "anon" actually is on Supabase, because the term undersells it. The anon role serves every request made with your project's public key: logged-out visitors of your app, yes — but also other people's scripts against your API, every crawler that found your endpoints, security researchers probing methodically, and anyone inspecting network tabs. The anon key is public by design; there is no gate before this role, only policies after it.
That reframing changes how the work feels. You're not configuring "logged-out behavior"; you're publishing an interface to everyone on earth, with the database enforcing the terms. Published interfaces deserve specifications:
- Which tables are visible at all?
- Which rows within them (published only? non-deleted? current versions)?
- Which columns (never internal flags, never personal identifiers)?
- What volume is acceptable per request?
- Which writes, if any, does the world get?
Answer those five and you have designed anonymous access. Leave any blank and you've inherited it instead — with the database's answer being whatever the absence of policies permits.
The five answers also compose into a testable spec, which is what separates design from theater. Each bullet translates directly to a probe: tables → sweep, rows → draft-probe, columns → select-star check, volume → page-walk, writes → insert attempt. By the final section, every question answered in this list has an automated or manual verification attached — design and proof in one artifact.
What anon can touch before you write anything
One clarifying fact makes the design easier: by default, once RLS is enabled, anon sees nothing. Default-deny applies to every role without matching policies, so the blank-slate posture costs one flag per table. The exposure risk comes from three specific gaps, each worth checking in your own project today:
- Tables with
rls_enabled = false— fully readable (the open-window pattern). - Policies targeting
anonmore broadly than intended — usually inherited from copy-paste. - Tautology policies (
using (true)) that were meant for authenticated but target PUBLIC, catching anon too.
A quick sweep finds all three:
select c.relname,
c.relrowsecurity as rls_enabled,
(select count(*) from pg_policies p
where p.schemaname='public' and p.tablename=c.relname) as policy_count,
(select count(*) from pg_policies p
where p.schemaname='public' and p.tablename=c.relname
and 'anon' = any(p.roles::text[])) as anon_policy_count
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
where n.nspname = 'public' and c.relkind = 'r'
order by c.relname;
Every row is a decision point: should the world reach this table at all? If yes, through exactly which rows and columns? If no, is its protection currently proven?
Reading the sweep's output is a three-way sort. Tables with anon_policy_count = 0 and RLS enabled are closed — correct for private data, suspicious if the product clearly serves logged-out visitors content (something is broken or bypassed). Tables with anon_policy_count >= 1 are open by policy — each deserves its clause read against the five-question spec above. Tables with rls_enabled = false are open by omission regardless of intent — the bucket-one triage from every other article here, fixed first.
The sweep also surfaces accidental PUBLIC targeting: a policy whose roles column shows {PUBLIC} applies to every role including service paths you assumed exempt. Copy-pasted policies frequently carry broader role lists than their new home deserves; this query makes them visible in one pass.
Designing the public read
The canonical case: content that logged-out visitors should see in published form only. The pattern, runnable as printed:
create table articles (
id uuid primary key default gen_random_uuid(),
author_id uuid not null,
title text not null,
body text not null,
status text not null default 'draft',
internal_notes text,
published_at timestamptz
);
alter table articles enable row level security;
create policy "articles_public_read"
on articles for select
to anon, authenticated
using (
status = 'published'
and published_at is not null
and published_at <= now()
);
Three deliberate choices live in that USING clause. Status plus timestamp means scheduled posts stay hidden until their moment — filtering on publication state, not just a boolean. The clause excludes drafts unconditionally, so "almost finished" never leaks. And because the policy targets both roles, signed-in authors need their own additional policy to see drafts:
create policy "articles_author_read"
on articles for select
to authenticated
using ((select auth.uid()) = author_id);
Permissive policies OR together, so authors now see published-plus-their-own while the world sees published-only — union semantics working for the design for once.
Two filter extensions appear constantly in real products, and both slot into the same clause. Scheduled content: published_at <= now() already handles it — future-dated rows exist but stay invisible until their timestamp passes, no cron required. Soft deletes: if the table carries deleted_at, add and deleted_at is null to the same policy; anonymous visitors never see tombstones, while authors' separate policy can include or exclude them by the same technique. Each additional business rule is one more AND inside USING — which also means each one deserves an index-conscious check as tables grow, per the performance guide.
Column scoping is the part teams forget. Row filters hide forbidden rows, but any returned row exposes all its columns — including internal_notes above, had we left it in the table. When public content carries private fields alongside, split them: move notes to a separate table keyed to the article, or serve the public surface through a narrowed view:
create view public_articles
with (security_invoker = true) as
select id, title, body, published_at
from articles
where status = 'published';
The view combines column narrowing with invoker semantics (so underlying policies still apply), giving the public surface exactly two dimensions of constraint — rows and columns — instead of one.
A note on when the split-table approach beats the view: views constrain what the public sees, but the columns still exist in the base table where broader-reading policies might expose them later. Physical separation — notes in their own table with owner-scoped policies — makes the private data structurally unreachable from the public path, not just filtered. Views are faster to ship; separation is harder to regress. Choose by how sensitive the fields are and how many future policies will touch the table.
Keeping writes closed
Unless the product deliberately needs otherwise, the write side of anonymous access is simply: nothing. Default deny delivers that for free — no anon-targeted INSERT/UPDATE/DELETE policies means every anonymous write fails at the policy layer, provably:
begin;
set local role anon;
insert into articles (author_id, title, body)
values ('00000000-0000-0000-0000-000000000000', 'spam', 'x');
rollback;
Expected: rejection. Run it monthly; run it in CI; this single probe is the entire guarantee.
When anonymous writes genuinely belong in the product — contact forms, comment-if-you-have-email approval flows — design them as narrow chutes rather than doors: dedicated tables accepting only sanitized fields, no identifiers the client controls, validation server-side, and rate limiting in front. A contact form's anonymous insert into contact_requests(name, message) is a feature; anonymous inserts into your main content tables are a spam-and-forgery surface. The distinction is which table, not which role. And when anonymous visitors need to write data tied to themselves rather than into a queue, you are building anonymous accounts — a product decision with abuse implications (captcha, verification, rate limits) worth making consciously rather than inheriting from default-open tables.
Chute design has three properties worth enforcing explicitly. Isolation: the chute table holds nothing sensitive and joins to nothing sensitive, so flooding it degrades nothing but itself. Inertness: rows written anonymously stay invisible until a privileged actor processes them — no policies ever serve raw submissions publicly. Hygiene: cleanup jobs prune old unprocessed entries so the chute can't become an unbounded dump. Together these turn "the internet can write here" from a threat model problem into a bounded, monitored queue — which is what every deliberate anonymous-write feature actually is.
Abuse resistance for public surfaces
Public reads face a different threat model than private ones: not unauthorized access but unauthorized scale. Three mitigations, in effectiveness order:
Server-side result caps. PostgREST honors row limits configured per project; application-level page sizes mean nothing to a script paging through everything. Cap what any single request may return.
Rate limiting at the edge. Platform-level throttling (or a CDN/WAF in front) turns bulk enumeration expensive. This protects infrastructure availability too — anon traffic has no account to throttle individually.
Enumeration hygiene. Sequential or guessable identifiers let callers iterate systematically even with caps. Where content is public-but-not-bulkable, random UUIDs or scoped tokens raise iteration cost substantially.
Response discipline. Public endpoints should return consistent shapes for found and not-found cases — a missing row and an unauthorized row should be indistinguishable. Policies already deliver this at the database layer (filtered rows simply don't exist as far as the response is concerned), which is one of RLS's quiet gifts: no conditional error design needed, no existence oracle leaking through distinct messages.
None of these replace policies; they complement them, addressing volume rather than visibility. A published catalog that someone mirrors wholesale is a business decision; an internal notes table leaked because it sat adjacent to public ones is an incident — policies prevent the second, limits blunt the first.
Caching adds a wrinkle worth deciding rather than inheriting: responses to anonymous requests are trivially cacheable, which CDNs will do aggressively given permissive headers. Cached public content is usually fine — until a policy fix ships and stale cached rows keep serving old visibility for the cache lifetime. Deliberate anonymous access includes knowing what's cached, where, and for how long, so that tightening rules includes flushing the edge.
The verification checklist
Deliberate anonymous access stays deliberate through periodic proof:
| Check | Method | Pass |
|---|---|---|
| Only intended tables respond to anon | Sweep all exposed tables with anon GET | Others return empty/denied |
| Filters hold | Probe known-draft/unpublished rows as anon | Absent |
| Writes closed | Attempt anon insert/update/delete | All rejected |
| Columns scoped | Request select=* on public tables | No private fields in response |
| Volume sane | Page-walk a public table | Caps engage; full-table walk impractical |
Five checks, fifteen minutes, quarterly — or automated continuously as part of an outside-in scan (what the free probe covers). Anonymous access done deliberately isn't fragile; it just requires the same evidence habit as everything else in this catalog: claims verified, boundaries probed, drift caught between deploys rather than discovered by users.
Document the decisions alongside the checks. A one-page "public surface" spec — tables, row filters, columns, limits, last-reviewed date — turns every future question ("can the world see X?") into a lookup instead of an investigation. It also makes handoffs survivable: the next maintainer inherits a spec instead of reverse-engineering intent from policy expressions.
Common questions
Is having any anonymous access a red flag?
No — it's frequently correct. Public content is how discovery works: docs, listings, blog posts, product catalogs all want anonymous reads. The red flag isn't anonymous access existing; it's existing unexamined — tables responding to anon that nobody remembers deciding to publish.
Can't I just disable the anon key?
There's nothing to disable — the key identifies the project for all public traffic, including your logged-out app users bootstrapping sessions. What you control is the privilege attached: zero anon-targeted policies equals zero anonymous access, regardless of key distribution. Disable access in policies, where it belongs.
Should anonymous users share the authenticated policy if filters make it equivalent?
Prefer explicit: list anon in policies intended for it and keep authenticated-only rules separate. A policy targeting both roles reads as "this is genuinely public," while shared-by-accident targeting (omitting the TO clause entirely, which defaults to PUBLIC) reads as an oversight — to reviewers now and to auditors later. Explicitness costs one word per policy.
We have public read today with using (true). Is changing it risky?
The risk is backwards: tightening reveals whether features depended on over-width. Audit first what anon actually fetches (logs), write the precise filter, deploy behind a test, and watch for breakage reports from the exact surfaces documented to use public data. Teams rarely find legitimate consumers beyond the intended ones — but when they do, that's an undocumented dependency better found now than during the next incident review.
How does anonymous access interact with Realtime?
The same policies govern live streams: a subscriber holding only the anon key receives postgres-changes events filtered exactly as their SELECT policies dictate. That means your published-only filter extends to realtime automatically — drafts never appear in feeds — but also that tautology policies stream everything, live, to everyone. Test subscriptions with the same two-persona rigor you apply to REST reads.
Curious what anonymous visitors can reach in your project right now? Run the free scan — paste your app URL and see your public surface exactly as the outside world does.
RowShield is an independent product and is not affiliated with, endorsed by, or sponsored by Supabase, Inc.