0
Challenge · 66The Data API & Your Next.js App
RPC: when logic belongs in the database
Queriesused in ~75% of apps
Liking a post is two writes: record that you liked it, and bump the count everyone sees. Do that as two `.from()` calls from the browser and you have shipped a bug that never throws — PostgREST has no multi-statement transaction API, so nothing connects call one to call two. The fix is not "be careful." It is to stop sending Postgres a list of instructions and instead ask it to run one, by name.
Core idea. supabase.rpc(name, args) calls a Postgres function over the Data API and hands back whatever it returns. Wrapping several statements inside that function makes them one implicit transaction — the whole thing commits or none of it does, which a sequence of separate REST calls can never promise. The function still runs as SECURITY INVOKER (the default) or SECURITY DEFINER (concept 37), and that choice inside an RPC matters more than almost anywhere else in the app, because RPCs are exactly the place business logic needs to touch rows the caller does not own.
poke it, drag it,
try to break it
try to break it
no slides here.
you drive.
you drive.
Playground, this isn't a screenshot
1. insert like
await supabase.from('likes').insert({ post_id, user_id })2. increment count
await supabase.from('posts').update({ like_count: n + 1 }).eq('id', post_id)Consistent. Nothing interrupted this run — both calls completed, so the count happens to match. That is luck, not a guarantee: nothing connects call 1 to call 2.
↑ play a little first, then dig in