Supabase Recipes: Auth, Row Level Security, Storage, Edge Functions and Realtime
supabase-recipes is a collection of practical, copy-paste Supabase recipes for developers building apps on Supabase (Postgres, Auth, Storage, Edge Functions and Realtime). It covers sign-up and sign-in flows, Row Level Security (RLS) policies for per-user, public and team-based data, storage bucket policies with per-user folders and signed URLs, Edge Functions secured with the new API keys, private Realtime channels with Broadcast and Presence, typed supabase-js queries, Next.js server-side auth, the Supabase CLI and a security checklist.
What makes it different: the SQL recipes are real migrations in supabase/migrations/, and the RLS policies are tested by an automated suite that runs every migration in PGlite (Postgres compiled to WebAssembly) and then acts as different users to prove who can read and write what. The TypeScript examples are type-checked against supabase-js.
Last reviewed: December 2026, against supabase-js 2.120, @supabase/ssr 0.12, @supabase/server 1.9 and Supabase CLI 3.4. Supabase moves fast: API keys, CLI flags and Edge Function helpers changed during 2025 and 2026, so check the Supabase docs when something does not match.
git clone https://github.com/Ralpberry-Labs/supabase-recipes
cd supabase-recipes
npm install
npm test # runs all migrations in PGlite and checks every RLS policy (8 test groups)
npm run typecheck # type-checks the supabase-js and Next.js examples
Table of Contents
- What Is Inside
- Supabase in Five Minutes
- API Keys: Publishable vs Secret
- Local Development with the CLI
- Auth Recipes
- Server-Side Auth (Next.js)
- Row Level Security: The Mental Model
- RLS Recipes
- RLS Performance
- Testing RLS
- Database Recipes
- Querying with supabase-js
- Storage Recipes
- Edge Functions Recipes
- Scheduled Jobs and Webhooks
- Realtime Recipes
- Supabase CLI Cheat Sheet
- Security Checklist
- Common Errors and Fixes
- Supabase vs Firebase vs Alternatives
- FAQ
- Where to Go Next
- Contributing
- License
- More free resources
What Is Inside
| Path | Recipe |
|---|---|
supabase/migrations/..._profiles.sql |
Profiles table filled by a sign-up trigger; public read, owner update; column-level grants; updated_at trigger |
supabase/migrations/..._todos.sql |
Per-user data with four RLS policies, an index, a security_invoker view and an RPC |
supabase/migrations/..._teams.sql |
Multi-tenant teams with owner/admin/member roles using security definer helpers in a private schema |
supabase/migrations/..._storage.sql |
Public avatars and private documents buckets with per-user folder policies |
supabase/migrations/..._realtime.sql |
Private Realtime channels per team; Postgres Changes publication |
supabase/migrations/..._payments.sql |
Server-written, user-readable data (webhook pattern) |
supabase/functions/ |
Edge Functions: user-scoped API, secret-key cron job, Stripe webhook, plain supabase-js version |
supabase/config.toml |
Config excerpt (verify_jwt, bucket settings) |
snippets/schedule-edge-function.sql |
pg_cron + pg_net + Vault to call a function nightly |
examples/client-recipes.ts |
Typed supabase-js: auth, queries, pagination, RPC, storage, realtime, functions |
examples/nextjs/ |
@supabase/ssr clients, proxy.ts session refresh, a Server Component |
tests/rls.test.mjs |
The RLS test suite (PGlite + a small Supabase stub) |
Tested: npm test passes 8 test groups against PGlite (Postgres 19 in WebAssembly) with a stub of the Supabase auth, storage and realtime schemas, and the suite fails if you loosen a policy (checked by mutating policies). npm run typecheck passes with TypeScript 7. The Edge Functions (Deno) and the Next.js app were not executed during review; they follow the current Supabase documentation patterns.
Supabase in Five Minutes
| Product | What it is | You use it for |
|---|---|---|
| Database | A full Postgres database per project | Tables, SQL, extensions (pgvector, PostGIS, pg_cron) |
| Data API | Auto-generated REST (PostgREST) and GraphQL APIs over your schema | Query from clients with supabase-js |
| Auth | Users, sessions, JWTs; email, magic links, OAuth, phone, SSO, MFA, anonymous sign-in | Sign-in; RLS uses the user’s ID from the JWT |
| Storage | S3-compatible file storage with policies in Postgres | Avatars, uploads, private documents |
| Edge Functions | TypeScript functions on Deno, deployed globally | Webhooks, server logic, third-party APIs with secrets |
| Realtime | WebSocket channels: Postgres Changes, Broadcast, Presence | Live updates, chat, cursors, who is online |
| Vector | pgvector and helpers | Embeddings and semantic search |
| Queues, Cron | pgmq and pg_cron integrations | Background jobs, schedules |
The key idea: your browser or mobile app talks directly to the database through the Data API, so Row Level Security is your backend authorization. Every table exposed to clients needs RLS policies.
API Keys: Publishable vs Secret
| Key | Format | Postgres role | Where it may live |
|---|---|---|---|
| Publishable | sb_publishable_... |
anon, or authenticated when the request also carries a user JWT |
Anywhere: browser, mobile app, public repo |
| Secret | sb_secret_... |
service_role (bypasses RLS) |
Only servers, Edge Functions, cron jobs; never in client code |
anon (legacy) |
Long JWT starting eyJ |
anon |
Legacy equivalent of publishable |
service_role (legacy) |
Long JWT | service_role |
Legacy equivalent of secret |
Supabase’s documentation says the legacy anon and service_role keys are being deprecated in early 2027; new and old keys work side by side until you disable the legacy ones, so you can migrate gradually. Recipes in this repo use the new keys.
Rules:
- The publishable key is public by design: it identifies your app, not a user. Security comes from RLS plus the user’s JWT.
- A secret key in a frontend bundle is a full database compromise. Rotate it immediately if it leaks (create a new secret key, deploy it, delete the old one).
- Send API keys in the
apikeyheader, user tokens inAuthorization: Bearer <jwt>. New keys are not JWTs.
Local Development with the CLI
The Supabase CLI runs the whole stack locally in Docker (Postgres, Auth, Storage, Realtime, Studio, Edge Runtime).
npm install -D supabase # or: brew install supabase/tap/supabase
npx supabase init # creates supabase/ (config.toml, migrations/, functions/)
npx supabase start # starts the local stack, prints URLs and local keys
npx supabase status
# Studio (dashboard) runs on http://localhost:54323 by default
npx supabase migration new add_todos # creates supabase/migrations/<timestamp>_add_todos.sql
npx supabase db reset # recreate the local DB from all migrations + seed.sql
npx supabase db diff -f add_index # save schema changes made in Studio as a migration
npx supabase gen types > examples/database.types.ts # TypeScript types from the local DB (CLI v3)
npx supabase login
npx supabase link --project-ref <ref>
npx supabase db push --remote --dry-run # preview what would be applied to the linked project
npx supabase db push --remote # apply new migrations to the linked project
npx supabase functions serve # run Edge Functions locally
npx supabase functions deploy my-todos
npx supabase secrets set STRIPE_SECRET_KEY=sk_test_...
npx supabase stop
CLI v3 note. Supabase CLI 3.0 (November 2026) made most database commands target the local stack by default and use --remote (optionally --remote=<ref|branch|url>) for hosted projects. Older v2 commands such as supabase gen types typescript --local and supabase db push (which pushed to the linked project) behave differently; check supabase <command> --help for your installed version.
Recommended workflow:
- Change the schema with a new migration file (or in local Studio, then
db diff -f). supabase db resetto replay everything from scratch; fix errors.- Run tests (
supabase test dbfor pgTAP, or this repo’s PGlite suite). - Regenerate types, commit migration + types.
- Push to staging (a branch or separate project), then production, from CI.
Auth Recipes
All snippets are from examples/client-recipes.ts unless noted.
Email and password sign-up with profile data
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
data: { username }, // stored in raw_user_meta_data
emailRedirectTo: 'https://example.com/auth/callback', // must be in Auth > URL Configuration
},
})
The on_auth_user_created trigger in the profiles migration copies username into public.profiles. Never use user_metadata for authorization: users can change it. Use app_metadata (server-set) or your own tables.
Other sign-in methods
await supabase.auth.signInWithPassword({ email, password })
await supabase.auth.signInWithOtp({ email }) // magic link or code
await supabase.auth.signInWithOtp({ phone: '+15555550123' }) // SMS (needs a provider)
await supabase.auth.verifyOtp({ email, token: '123456', type: 'email' }) // code entry
await supabase.auth.signInWithOAuth({ provider: 'github', options: { redirectTo } })
await supabase.auth.signInAnonymously() // guests; enable in settings
await supabase.auth.resetPasswordForEmail(email, { redirectTo })
await supabase.auth.updateUser({ password: newPassword }) // after the reset link
await supabase.auth.signOut()
Which “get user” method?
| Method | Verifies the token? | Network call | Use for |
|---|---|---|---|
getClaims() |
Yes (locally with asymmetric signing keys, else via Auth server) | Usually no | Server-side authorization checks: the default choice |
getUser() |
Yes (asks the Auth server) | Yes | When you need the latest user record (for example, a just-changed email or a banned user) |
getSession() |
No: reads storage/cookies | No | Client-side UI only; never trust it on a server |
React to sign-in and sign-out
const { data } = supabase.auth.onAuthStateChange((event, session) => {
// INITIAL_SESSION, SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, USER_UPDATED, PASSWORD_RECOVERY
})
data.subscription.unsubscribe() // on unmount
Do not await other Supabase calls directly inside this callback; schedule them (for example with setTimeout) to avoid deadlocks, as the supabase-js docs advise.
Roles in the JWT with a custom access token hook
To put an app role into every token (for RLS and UI), add a Postgres function and enable it under Authentication > Hooks:
create table public.user_roles (
user_id uuid primary key references auth.users (id) on delete cascade,
role text not null check (role in ('admin', 'editor'))
);
alter table public.user_roles enable row level security;
create function public.custom_access_token_hook(event jsonb)
returns jsonb
language plpgsql
stable
as $$
declare
claims jsonb := event -> 'claims';
user_role text;
begin
select role into user_role from public.user_roles where user_id = (event ->> 'user_id')::uuid;
claims := jsonb_set(claims, '{user_role}', coalesce(to_jsonb(user_role), 'null'::jsonb));
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 select on table public.user_roles to supabase_auth_admin;
create policy "Auth admin reads roles" on public.user_roles
as permissive for select to supabase_auth_admin using (true);
Then policies can check (select auth.jwt() ->> 'user_role') = 'admin'. Claims refresh only when the token refreshes, so role changes take effect after the next refresh (default token lifetime: one hour).
Multi-factor authentication
Enroll TOTP with supabase.auth.mfa.enroll({ factorType: 'totp' }), then challenge and verify. Require it in RLS with a restrictive policy:
create policy "Require MFA for updates"
on public.profiles as restrictive for update to authenticated
using ((select auth.jwt() ->> 'aal') = 'aal2');
Server-Side Auth (Next.js)
Server rendering needs the session in cookies, handled by @supabase/ssr. The files in examples/nextjs/:
| File | Role |
|---|---|
lib/supabase/client.ts |
createBrowserClient for Client Components (a singleton) |
lib/supabase/server.ts |
createServerClient with cookies() for Server Components, Actions, Route Handlers |
proxy.ts |
Refreshes the session on every request (Next.js 16 proxy.ts; middleware.ts on Next.js 15 and earlier) |
app/todos/page.tsx |
Server Component reading the user’s todos |
The proxy is the critical piece:
const supabase = createServerClient(url, publishableKey, {
cookies: {
getAll() { return request.cookies.getAll() },
setAll(cookiesToSet, headers) {
cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
supabaseResponse = NextResponse.next({ request })
cookiesToSet.forEach(({ name, value, options }) => supabaseResponse.cookies.set(name, value, options))
Object.entries(headers).forEach(([k, v]) => supabaseResponse.headers.set(k, v)) // no CDN caching of sessions
},
},
})
const { data } = await supabase.auth.getClaims() // refreshes and verifies
return supabaseResponse // the response setAll built last
Pitfalls that sign users out at random: returning a different response object than the one setAll created (copy its cookies and cache headers if you must), refreshing the token in two places at once, and running code between createServerClient and getClaims(). Environment variables: NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY.
The same package supports SvelteKit, Astro, Remix/React Router, Nuxt and other frameworks; only the cookie adapter differs.
Row Level Security: The Mental Model
A request reaches a row only if both layers allow it:
- Grants: does the role (
anon,authenticated) have privileges on the table? Missing grant givespermission denied. - RLS policies: which rows can it see or change? No matching policy gives empty results (reads) or
new row violates row-level security policy(writes).
| Clause | Applies to | Meaning |
|---|---|---|
using (...) |
select, update, delete |
Which existing rows are visible/targetable |
with check (...) |
insert, update |
What a new or modified row must satisfy |
to authenticated |
Role filter | Skip the policy entirely for other roles (faster, clearer) |
as restrictive |
Combination | Must pass in addition to permissive policies (AND instead of OR) |
Policies for the same command are combined with OR (permissive). RLS enabled with no policies means no access for anon/authenticated; the secret key (service_role) bypasses RLS.
Supabase’s docs note that on existing projects new tables in public get grants for anon and authenticated automatically, and that the platform is moving to opt-in exposure. Write explicit grant statements in the same migration as your policies, as every recipe here does, and your schema behaves the same either way.
RLS Recipes
1. Each user owns their rows
create table public.todos (
id bigint generated always as identity primary key,
user_id uuid not null default auth.uid() references auth.users (id) on delete cascade,
title text not null
);
create index todos_user_id_idx on public.todos (user_id);
alter table public.todos enable row level security;
grant select, insert, update, delete on public.todos to authenticated;
create policy "read own" on public.todos for select to authenticated using ((select auth.uid()) = user_id);
create policy "insert own" on public.todos for insert to authenticated with check ((select auth.uid()) = user_id);
create policy "update own" on public.todos for update to authenticated
using ((select auth.uid()) = user_id) with check ((select auth.uid()) = user_id);
create policy "delete own" on public.todos for delete to authenticated using ((select auth.uid()) = user_id);
The update policy needs both clauses: using stops editing others’ rows, with check stops handing your row to someone else.
2. Public read, owner write
grant select on public.profiles to anon, authenticated;
grant update (username, full_name, avatar_url) on public.profiles to authenticated; -- column-level
create policy "anyone reads" on public.profiles for select to anon, authenticated using (true);
create policy "owner updates" on public.profiles for update to authenticated
using ((select auth.uid()) = id) with check ((select auth.uid()) = id);
Column-level grants stop users from editing columns such as is_verified even on their own row.
3. Teams / organizations (multi-tenant)
Put membership checks in security definer functions in a non-exposed schema. They read team_members without triggering its own policies (avoiding infinite recursion) and Postgres can cache them per statement:
create function private.is_team_member(p_team_id uuid)
returns boolean language sql stable security definer set search_path = '' as $$
select exists (
select 1 from public.team_members m
where m.team_id = p_team_id and m.user_id = (select auth.uid())
);
$$;
create policy "Members can read team projects"
on public.projects for select to authenticated
using ((select private.is_team_member(team_id)));
The full recipe (teams.sql) adds roles (owner, admin, member), makes the creator the owner with a trigger, lets admins add members but not owners, and lets anyone leave. The tests check that non-members see nothing and that access disappears when a member leaves.
4. Role-based access from JWT claims
create policy "Admins read everything"
on public.orders for select to authenticated
using ((select auth.jwt() ->> 'user_role') = 'admin');
-- app_metadata is set server-side only (admin API or SQL), so users cannot forge it
create policy "Staff by app_metadata"
on public.reports for select to authenticated
using (((select auth.jwt()) -> 'app_metadata' ->> 'staff')::boolean is true);
5. Server-only writes, user reads
Grant users select only; insert from an Edge Function with the secret key (payments.sql):
grant select on public.payments to authenticated;
create policy "read own payments" on public.payments for select to authenticated
using ((select auth.uid()) = user_id);
6. Shared rows (two parties)
create policy "buyer or seller can read" on public.orders for select to authenticated
using ((select auth.uid()) in (buyer_id, seller_id));
7. Views that respect RLS
Views run with their owner’s rights by default, bypassing RLS. On Postgres 15+ (all current Supabase projects):
create view public.todo_stats with (security_invoker = true) as
select user_id, count(*) as total from public.todos group by user_id;
8. Soft deletes
alter table public.todos add column deleted_at timestamptz;
create policy "hide deleted" on public.todos as restrictive for select to authenticated
using (deleted_at is null);
Common RLS mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| RLS not enabled on an exposed table | Anyone with the publishable key can read and write it | alter table ... enable row level security; check the Security Advisor |
Policy with no to clause |
Runs for anon too |
Add to authenticated |
update policy without with check |
Users can change user_id to someone else |
Add with check |
Using user_metadata for permissions |
Users edit their own metadata | Use app_metadata, a roles table or a hook |
| Policies that query each other’s tables | infinite recursion detected in policy |
Use security definer helpers |
security definer function in public |
Callable by anyone over the API with elevated rights | Put it in a non-exposed schema, set search_path = '' |
Views without security_invoker |
Leak rows | with (security_invoker = true) |
Trusting getSession() on the server |
Forged cookies accepted | getClaims() |
| Using the secret key in the browser | Bypasses all RLS | Publishable key only |
RLS Performance
| Tip | Why |
|---|---|
Wrap functions: (select auth.uid()) instead of auth.uid() |
Evaluated once per statement (initPlan) instead of per row |
Index policy columns (user_id, team_id) |
Policies are WHERE clauses |
Add to authenticated |
Skips the policy for other roles |
Also filter in the query (.eq('user_id', id)) |
Lets Postgres use indexes before applying the policy |
Use security definer helpers for joins to membership tables |
Avoids running RLS on the joined table for every row |
Prefer team_id in (select ...) over correlated joins on large tables |
Better plans |
Check plans with explain analyze while impersonating a user (see testing), and run supabase db advisors or the dashboard’s Performance and Security Advisors.
Testing RLS
This repo’s approach (no Docker): tests/rls.test.mjs loads a small stub of Supabase’s auth, storage and realtime schemas (tests/supabase_stub.sql) into PGlite, applies every migration, creates two users, then runs queries as each one:
async function as(userId, fn) {
return db.transaction(async (tx) => {
await tx.query(`select set_config('request.jwt.claims', $1, true)`,
[JSON.stringify({ sub: userId, role: 'authenticated' })])
await tx.exec('set local role authenticated')
return fn(tx)
})
}
const theirs = await as(BOB, (tx) => tx.query(`update public.todos set title = 'x' where title like 'alice%'`))
assert.equal(theirs.affectedRows, 0) // Bob cannot touch Alice's rows
It covers profiles, todos (including insert spoofing and anon access), the view and RPC, teams (non-members, self-joining, role escalation, leaving), realtime topic authorization, storage folders and payments.
The official approach: pgTAP tests in supabase/tests/*.sql, run with supabase test db against the local stack. The same trick applies inside SQL:
begin;
select plan(1);
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"11111111-1111-4111-8111-111111111111","role":"authenticated"}', true);
select is((select count(*) from public.todos)::int, 2, 'Alice sees her 2 todos');
select * from finish();
rollback;
Community helpers such as supabase-test-helpers add functions for creating test users and authenticating as them.
Database Recipes
Updated-at trigger
create function public.set_updated_at() returns trigger language plpgsql set search_path = '' as $$
begin new.updated_at := now(); return new; end; $$;
create trigger profiles_set_updated_at before update on public.profiles
for each row execute function public.set_updated_at();
RPC (Postgres functions callable from the client)
create function public.toggle_todo(todo_id bigint) returns public.todos
language sql set search_path = '' as $$
update public.todos set is_done = not is_done where id = todo_id returning *;
$$;
revoke execute on function public.toggle_todo(bigint) from public, anon;
grant execute on function public.toggle_todo(bigint) to authenticated;
const { data } = await supabase.rpc('toggle_todo', { todo_id: 42 })
Functions are security invoker by default, so RLS still applies inside. Use security definer only when you need elevated access, and then always set search_path = ''.
Full-text search
alter table public.articles add column fts tsvector
generated always as (to_tsvector('english', coalesce(title, '') || ' ' || coalesce(body, ''))) stored;
create index articles_fts_idx on public.articles using gin (fts);
const { data } = await supabase.from('articles').select('id, title').textSearch('fts', 'postgres & security', { type: 'websearch' })
Vector similarity search (pgvector)
create extension if not exists vector with schema extensions;
create table public.documents (id bigint generated always as identity primary key, content text,
embedding extensions.vector(1536));
create index on public.documents using hnsw (embedding extensions.vector_cosine_ops);
create function public.match_documents(query_embedding extensions.vector(1536), match_count int)
returns table (id bigint, content text, similarity float)
language sql stable set search_path = '' as $$
select d.id, d.content, 1 - (d.embedding operator(extensions.<=>) query_embedding) as similarity
from public.documents d
order by d.embedding operator(extensions.<=>) query_embedding
limit match_count;
$$;
Seed data
Put development data in supabase/seed.sql; supabase db reset runs it after migrations. Never seed real secrets.
Generated TypeScript types
npx supabase gen types > database.types.ts # local DB (CLI v3)
npx supabase gen types --remote > database.types.ts # linked project
Pass the type to createClient<Database>() and every .from(), .insert() and .rpc() is checked at compile time (examples/database.types.ts).
Querying with supabase-js
| Task | Code |
|---|---|
| Select columns | .from('todos').select('id, title') |
| Filter | .eq('is_done', false), .neq, .gt, .gte, .lt, .lte, .in('id', [1,2]), .is('deleted_at', null) |
| Text match | .ilike('title', '%milk%'), .textSearch('fts', 'milk') |
| OR | .or('is_done.eq.true,title.ilike.%urgent%') |
| JSON column | .eq('settings->>theme', 'dark') |
| Order and paginate | .order('created_at', { ascending: false }).range(0, 19) |
| Count | .select('*', { count: 'exact', head: true }) |
| One row | .single() (error if not exactly one), .maybeSingle() |
| Embedded relation | .select('id, name, teams ( name )') (uses foreign keys) |
| Insert and return | .insert({ title }).select().single() |
| Upsert | .upsert({ id, title }, { onConflict: 'id' }) |
| Update | .update({ title }).eq('id', id) |
| Delete | .delete().eq('id', id) |
| RPC | .rpc('toggle_todo', { todo_id: id }) |
| Abort / timeout | .abortSignal(AbortSignal.timeout(5000)) |
Always check error: supabase-js returns { data, error } instead of throwing. An empty data with no error usually means RLS filtered everything out.
Storage Recipes
Buckets are rows in storage.buckets; files are rows in storage.objects; access is controlled by RLS policies on storage.objects.
| Bucket type | Read | Write | Use for |
|---|---|---|---|
| Public | Anyone with the URL (no policy needed) | Policies | Avatars, product images |
| Private | Policies or signed URLs | Policies | Invoices, user documents |
Per-user folder convention (<user id>/<file>), from storage.sql:
create policy "Users upload their own documents"
on storage.objects for insert to authenticated
with check (
bucket_id = 'documents'
and (storage.foldername(name))[1] = (select auth.uid())::text
);
Client side:
// Upload (upsert replaces an existing file; needs an update policy too)
await supabase.storage.from('avatars').upload(`${userId}/avatar.png`, file, { upsert: true, contentType: 'image/png' })
// Public URL (public buckets)
const url = supabase.storage.from('avatars').getPublicUrl(`${userId}/avatar.png`).data.publicUrl
// Signed URL (private buckets), valid for 10 minutes
const { data } = await supabase.storage.from('documents').createSignedUrl(`${userId}/tax.pdf`, 600)
// Let a client upload without a session: signed upload URL created on the server
const { data: up } = await supabaseAdmin.storage.from('documents').createSignedUploadUrl(`${userId}/scan.pdf`)
// List, move, delete
await supabase.storage.from('documents').list(userId, { limit: 100 })
await supabase.storage.from('documents').move(`${userId}/a.pdf`, `${userId}/b.pdf`)
await supabase.storage.from('documents').remove([`${userId}/b.pdf`])
Tips:
- Set
file_size_limitandallowed_mime_typeson the bucket (done in the migration) instead of trusting the client. - For files larger than about 6 MB, Supabase recommends resumable uploads (TUS protocol) for reliability.
- Image transformations (resize on the fly with
transform: { width, height }) are available on paid plans. - Deleting a row in
storage.objectswith SQL does not delete the file; use the Storage API.
Edge Functions Recipes
Edge Functions are TypeScript on Deno. Create with supabase functions new name, run locally with supabase functions serve, deploy with supabase functions deploy name.
Choose how callers authenticate
The @supabase/server package’s withSupabase wrapper checks callers and gives you ready clients:
auth mode |
Accepts | verify_jwt |
Example in this repo |
|---|---|---|---|
'user' |
A signed-in user’s JWT in Authorization |
true (default) |
my-todos |
'secret' |
The secret key in apikey |
false |
cleanup-done-todos |
'publishable' |
The publishable key in apikey |
depends | Public-but-app-only endpoints |
'none' |
Anyone; you verify yourself | false |
stripe-webhook |
import { withSupabase } from 'npm:@supabase/server@1'
export default {
fetch: withSupabase({ auth: 'user' }, async (req, ctx) => {
// ctx.supabase: RLS-scoped to the caller; ctx.supabaseAdmin: bypasses RLS
const { data, error } = await ctx.supabase.from('todos').select('id, title')
if (error) return Response.json({ error: error.message }, { status: 500 })
return Response.json(data)
}),
}
Danger zone: ctx.supabaseAdmin sees every user’s rows. Filter by ctx.userClaims.id or use ctx.supabase.
Set verify_jwt = false per function in supabase/config.toml for webhooks and secret-key callers (config.toml).
Without the wrapper
plain-js-example does the same with Deno.serve, createClient and auth.getClaims(token), plus CORS handling for browser calls:
const supabase = createClient(Deno.env.get('SUPABASE_URL')!, publishableKey, {
global: { headers: { Authorization: req.headers.get('Authorization')! } },
})
const { data: claims } = await supabase.auth.getClaims(token)
Secrets and environment variables
npx supabase secrets set STRIPE_SECRET_KEY=sk_live_... STRIPE_WEBHOOK_SECRET=whsec_...
npx supabase secrets list
# local: supabase/functions/.env (gitignored), or --env-file
Available automatically on the platform: SUPABASE_URL, SUPABASE_PUBLISHABLE_KEYS and SUPABASE_SECRET_KEYS (JSON objects of named keys), SUPABASE_JWKS, SUPABASE_DB_URL, and the legacy SUPABASE_ANON_KEY / SUPABASE_SERVICE_ROLE_KEY.
Calling from the client
const { data, error } = await supabase.functions.invoke('my-todos', { method: 'POST', body: { title: 'hi' } })
Edge Function tips
- Use
npm:orjsr:specifiers for dependencies; pin major versions. - Keep functions small and stateless; there are CPU-time and memory limits per invocation.
- Return early on
OPTIONSwith CORS headers when browsers call the function directly. - Webhooks: verify signatures with the provider’s async API (Stripe’s
constructEventAsyncwithcreateSubtleCryptoProvider()on Deno). - Log with
console.log; read logs in the dashboard or withsupabase logs.
Scheduled Jobs and Webhooks
| Need | Tool |
|---|---|
| Run SQL on a schedule | pg_cron (cron.schedule('nightly', '0 3 * * *', 'delete from ...')) |
| Call an Edge Function on a schedule | pg_cron + pg_net (snippets/schedule-edge-function.sql) |
| React to inserts/updates by calling a URL | Database Webhooks (pg_net under the hood) |
| Background job queue with retries | Supabase Queues (pgmq) |
| Third-party events (Stripe, GitHub) | Edge Function with verify_jwt = false and signature checks |
Store URLs and keys used by cron jobs in Vault (vault.create_secret) rather than in plain SQL.
Realtime Recipes
| Feature | What it sends | Authorization |
|---|---|---|
| Postgres Changes | Row inserts, updates, deletes | Table RLS (each client gets only rows it may read); table must be in the supabase_realtime publication |
| Broadcast | Low-latency messages between clients (or from the database) | RLS on realtime.messages for private channels |
| Presence | Shared “who is online” state | RLS on realtime.messages for private channels |
Listen to database changes
alter publication supabase_realtime add table public.todos;
const channel = supabase
.channel('my-todos')
.on('postgres_changes', { event: '*', schema: 'public', table: 'todos' }, (payload) => {
console.log(payload.eventType, payload.new, payload.old)
})
.subscribe()
// filter server-side: { event: 'UPDATE', schema: 'public', table: 'todos', filter: 'is_done=eq.true' }
supabase.removeChannel(channel) // on unmount
Private Broadcast + Presence channel per team
Policies on realtime.messages decide who may join a topic (realtime.sql):
create policy "Team members can receive team broadcasts and presence"
on realtime.messages for select to authenticated
using (
realtime.messages.extension in ('broadcast', 'presence')
and (select private.is_team_member(private.team_id_from_topic((select realtime.topic()))))
);
await supabase.realtime.setAuth() // send the user's JWT to Realtime
const room = supabase.channel(`team:${teamId}`, { config: { private: true, presence: { key: userId } } })
room
.on('broadcast', { event: 'cursor' }, ({ payload }) => drawCursor(payload))
.on('presence', { event: 'sync' }, () => setOnline(Object.keys(room.presenceState())))
.subscribe(async (status) => {
if (status === 'SUBSCRIBED') await room.track({ name: 'Ada' })
})
room.send({ type: 'broadcast', event: 'cursor', payload: { x: 10, y: 20 } })
Disable “Allow public access” in the Realtime settings so every channel must be private and authorized. Do not run alter table realtime.messages enable row level security: RLS is already on and the statement fails because you do not own the table.
Broadcast from the database
select realtime.send(
payload => jsonb_build_object('todo_id', 42),
event => 'todo_completed',
topic => 'team:2f0c5c2e-0000-4000-8000-000000000000',
private => true
);
Use it inside a trigger to push changes to private channels (Supabase also provides realtime.broadcast_changes() for trigger-based broadcasting of row changes).
Supabase CLI Cheat Sheet
| Command (CLI v3) | Does |
|---|---|
supabase init |
Create supabase/ in your repo |
supabase start / stop / status |
Local stack in Docker |
supabase migration new <name> |
New empty migration |
supabase migration list |
Local vs applied migrations |
supabase db reset |
Rebuild local DB from migrations + seed |
supabase db diff -f <name> |
Generate a migration from schema changes |
supabase db push --remote |
Apply migrations to the linked project |
supabase db pull --remote |
Pull the remote schema into a migration |
supabase db dump --remote -f schema.sql |
Dump schema (or --data-only) |
supabase db advisors |
Security and performance checks |
supabase db lint |
Check functions for errors |
supabase test db |
Run pgTAP tests in supabase/tests |
supabase gen types / --remote |
TypeScript types (also --lang go, python, swift, dart) |
supabase link --project-ref <ref> |
Connect the folder to a hosted project |
supabase functions new/serve/deploy/list/delete |
Edge Functions |
supabase secrets set/list/unset |
Function secrets |
supabase branches |
Preview branches |
supabase logs |
Local or hosted logs |
supabase inspect |
Database inspection tools (bloat, locks, slow queries) |
Security Checklist
- RLS enabled on every table in exposed schemas (Security Advisor shows none missing).
- Explicit
grantstatements match what each role should reach; revoke the rest. - Every policy has a
torole; update policies havewith check. - No authorization decisions based on
user_metadata. security definerfunctions live in non-exposed schemas withset search_path = ''.- Views use
security_invoker = trueor are not exposed. - Secret keys only on servers; publishable key in clients; legacy keys disabled once migrated.
- Server code uses
getClaims()(orgetUser()), nevergetSession(), for auth decisions. - Storage buckets have size and MIME limits; private data in private buckets.
- Realtime: public access disabled if channels carry private data; policies on
realtime.messages. - Edge Functions: correct
authmode,verify_jwtset deliberately, webhook signatures verified. - Auth: redirect URL allow-list configured, email confirmation on, rate limits and CAPTCHA reviewed.
- Network restrictions and SSL enforcement for direct database connections in production.
- Point-in-time recovery or backups configured for production data.
- RLS tests in CI (pgTAP or a suite like this repo’s).
Common Errors and Fixes
| Error | Cause | Fix |
|---|---|---|
new row violates row-level security policy for table "x" |
Insert/update fails with check, or no insert policy |
Check the policy and that user_id matches auth.uid() |
Query returns [] with no error |
RLS filtered all rows, or not signed in | Check the session and select policy |
permission denied for table x |
Missing grant | grant select ... to authenticated |
infinite recursion detected in policy |
Policies referencing each other’s tables | security definer helper function |
JWT expired |
Long-lived tab without refresh | Let supabase-js auto-refresh; in SSR, refresh in the proxy |
| Users randomly signed out (SSR) | Response from proxy lost refreshed cookies, double refresh | Return the setAll response; refresh only in the proxy |
| Edge Function 401 | Key sent as Bearer, or verify_jwt on for a webhook |
API keys in apikey; verify_jwt = false where intended |
must be owner of table messages |
alter table realtime.messages ... in a migration |
Remove that statement |
| Realtime events not arriving | Table not in the publication, or RLS hides rows | alter publication supabase_realtime add table ... |
Bucket not found |
Typo or bucket not created in this environment | Create it in a migration / config.toml |
relation "public.x" does not exist from the client |
Table in a schema not exposed in API settings | Expose the schema or move the table |
Supabase vs Firebase vs Alternatives
| Supabase | Firebase | Appwrite | PocketBase | Convex | Neon | |
|---|---|---|---|---|---|---|
| Database | Postgres (SQL) | Firestore (NoSQL documents), Data Connect (Postgres) | Document-style collections | SQLite | Document DB with TypeScript functions | Serverless Postgres only |
| Authorization | Postgres RLS | Security Rules | Permissions per document | API rules | Code in functions | Bring your own (RLS possible) |
| Auth included | Yes | Yes | Yes | Yes | Via providers | Neon Auth add-on |
| Realtime | Yes | Yes | Yes | Yes | Yes (reactive queries) | No |
| Self-hosting | Yes (Docker) | No | Yes | Yes (single binary) | Yes (open source backend) | No |
| Best for | SQL-first apps, relational data | Mobile apps in the Google ecosystem | Self-hosted all-in-one | Tiny apps, prototypes | Reactive TypeScript apps | Postgres hosting with branching |
Pick Supabase when you want Postgres (joins, constraints, SQL, extensions) with batteries included and the option to leave with a standard database dump.
FAQ
Is it safe to expose the publishable (anon) key?
Yes, that is its purpose. It only grants what your grants and RLS policies allow the anon and authenticated roles. The secret key must never be exposed.
Do I need a backend server with Supabase? Often not: clients query the database directly under RLS. Add Edge Functions (or your own server) for secrets, third-party APIs, webhooks and logic you cannot express as policies.
Why does my query return an empty array?
RLS. Either the user is not signed in (role anon), or no select policy matches. Test the policy in the SQL editor while impersonating the user.
How do I make a user an admin?
Store roles in a table (or app_metadata), expose them in the JWT with a custom access token hook, and check them in policies. Never in user_metadata.
How do I run code when a user signs up?
A trigger on auth.users (the profiles recipe), an Auth hook, or a Database Webhook calling an Edge Function.
What is the difference between getUser, getSession and getClaims?
getClaims verifies the JWT (locally with asymmetric keys) and is the default for server-side checks; getUser asks the Auth server for the latest user; getSession reads local storage or cookies without verification.
Can I use Supabase with Prisma or Drizzle? Yes, they connect to Postgres directly (use the pooler connection string for serverless). Direct connections bypass the Data API, so RLS only applies if you connect as a role that is subject to it; server-side ORMs usually run as a privileged role, so enforce authorization in your code.
Does Supabase pause free projects? Free-plan projects can be paused after a period of inactivity, and paused projects can be restored from the dashboard; check the pricing page for current limits.
How do I migrate from Firebase? Supabase provides migration guides and tools for Auth users and Firestore data; plan the data model as relational tables rather than mirroring documents.
Can I self-host Supabase? Yes, with the official Docker Compose setup. Some platform features differ (for example, a single publishable and a single secret key).
Where to Go Next
- Read the official guides on Row Level Security and Securing your API.
- Set up server-side auth for your framework.
- Learn the Edge Functions auth patterns and the
@supabase/serverpackage. - Explore Realtime authorization for private channels.
- Add pgTAP tests with the testing overview.
- Copy a migration from this repo into your project, adapt the table names, and add a test case for every policy you write.
Contributing
PRs welcome. Recipes must be accurate for current Supabase releases (note the version when behaviour changed). New SQL recipes go in supabase/migrations/ with tests in tests/rls.test.mjs (npm test must pass); TypeScript examples must pass npm run typecheck.
License
MIT. See LICENSE.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.