checking customerInfo.entitlements.active in the app is fine for showing a "Pro" badge, but it can't protect premium data. Log users in to RevenueCat with their Supabase user ID, receive RevenueCat webhooks in a Supabase Edge Function, re-fetch the subscriber and store the entitlement in a subscriptions table that only the server can write. Then gate premium rows with an RLS policy that calls a small has_pro() function. The app gets instant feedback from the SDK; the database enforces access.
Most RevenueCat tutorials stop when the purchase succeeds. That works until premium content lives in your database: anyone with your anon key can query Supabase directly, and an in-app check doesn't stop them. This guide closes that gap.
The architecture
App (react-native-purchases)
│ purchase / restore
▼
App Store / Google Play ──► RevenueCat ──► webhook ──► Supabase Edge Function
│ re-fetch subscriber
▼
public.subscriptions (server-only writes)
│
RLS: premium tables check public.has_pro()
Two rules make it secure:
- Only the server writes subscription state. Clients can read their own row, never change it.
- Premium data is protected by RLS, not by hiding screens.
Step 1: Use the same user ID everywhere
After Supabase sign-in, log the user in to RevenueCat with their Supabase user ID, so every webhook maps straight to a row in your database:
// src/payments/revenuecat.ts
import { Platform } from 'react-native';
import Purchases from 'react-native-purchases';
export function configurePurchases() {
Purchases.configure({
apiKey: Platform.OS === 'ios'
? process.env.EXPO_PUBLIC_RC_IOS_KEY!
: process.env.EXPO_PUBLIC_RC_ANDROID_KEY!,
});
}
export async function identifyUser(supabaseUserId: string) {
await Purchases.logIn(supabaseUserId);
}
export async function resetUser() {
await Purchases.logOut();
}
Call identifyUser whenever a Supabase session starts, and resetUser on sign-out. react-native-purchases includes native code, so test in a development build.
Step 2: Create the subscriptions table
create table public.subscriptions (
user_id uuid primary key references auth.users (id) on delete cascade,
entitlement text not null default 'pro',
is_active boolean not null default false,
product_id text,
store text,
expires_at timestamptz,
updated_at timestamptz not null default now()
);
alter table public.subscriptions enable row level security;
-- Users can read their own subscription. No insert/update/delete policies:
-- only the service role (the webhook) can write.
create policy "Read own subscription"
on public.subscriptions for select to authenticated
using ( (select auth.uid()) = user_id );
create table public.processed_rc_events (
event_id text primary key,
processed_at timestamptz not null default now()
);
alter table public.processed_rc_events enable row level security;
Because there are no write policies, clients can't grant themselves a subscription, even with the anon key.
Step 3: A helper for policies
create or replace function public.has_pro()
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1 from public.subscriptions
where user_id = (select auth.uid())
and is_active
and (expires_at is null or expires_at > now())
);
$$;
Checking expires_at as well as is_active means access ends on time even if a webhook is delayed.
Step 4: Gate premium data with RLS
create policy "Pro users read premium lessons"
on public.premium_lessons for select to authenticated
using ( public.has_pro() );
Now a non-subscriber's query for premium lessons returns nothing, whether it comes from your app, a modified app or curl.
Step 5: Receive RevenueCat webhooks
In RevenueCat, add a webhook pointing to your Edge Function and set an authorization header value. RevenueCat sends it with every request, so you can reject anything else.
Webhooks can arrive late, twice or out of order, so treat each one as a signal and re-fetch the subscriber's current state from RevenueCat's REST API instead of trusting the event payload:
// supabase/functions/revenuecat-webhook/index.ts
import { createClient } from 'npm:@supabase/supabase-js@2';
const admin = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
);
Deno.serve(async (req) => {
if (req.headers.get('Authorization') !== Deno.env.get('RC_WEBHOOK_AUTH')) {
return new Response('Unauthorized', { status: 401 });
}
const { event } = await req.json();
// Ignore sandbox events in production
if (event.environment === 'SANDBOX' && Deno.env.get('APP_ENV') === 'production') {
return new Response('ignored');
}
// Idempotency: handle each event once
const { error: dupError } = await admin
.from('processed_rc_events')
.insert({ event_id: event.id });
if (dupError) return new Response('duplicate');
const userId = event.app_user_id;
// Re-fetch the current state from RevenueCat
const res = await fetch(
`https://api.revenuecat.com/v1/subscribers/${encodeURIComponent(userId)}`,
{ headers: { Authorization: `Bearer ${Deno.env.get('RC_SECRET_KEY')}` } }
);
if (!res.ok) return new Response('RevenueCat error', { status: 502 });
const { subscriber } = await res.json();
const pro = subscriber.entitlements?.pro;
const expiresAt = pro?.expires_date ?? null;
const isActive = !!pro && (expiresAt === null || new Date(expiresAt) > new Date());
await admin.from('subscriptions').upsert({
user_id: userId,
entitlement: 'pro',
is_active: isActive,
product_id: pro?.product_identifier ?? null,
store: event.store ?? null,
expires_at: expiresAt,
updated_at: new Date().toISOString(),
});
return new Response('ok');
});
Deploy it without requiring a user JWT, since RevenueCat calls it directly; the authorization header is the protection. If anonymous RevenueCat users can purchase before signing in, handle TRANSFER and aliasing events so purchases end up on the right Supabase user.
Step 6: Instant UI without waiting for the webhook
The SDK knows about a purchase immediately; the webhook can take a few seconds. Use both:
import Purchases, { CustomerInfo } from 'react-native-purchases';
// Instant UI: unlock screens as soon as the SDK reports the entitlement
Purchases.addCustomerInfoUpdateListener((info: CustomerInfo) => {
const isPro = info.entitlements.active['pro'] !== undefined;
setIsPro(isPro);
});
Then, after a successful purchase, refetch premium queries once the subscriptions row updates. A Supabase Realtime subscription on the user's own row (which RLS allows) or a short retry both work. If the gap matters in your app, add a small "sync" Edge Function that runs the same re-fetch immediately after purchase.
The rule of thumb: the SDK drives the UI; the database decides access.
Step 7: Test the whole loop
- Buy with a sandbox account (iOS) or license tester (Android) in a development build.
- Check the webhook ran and the
subscriptionsrow showsis_active = true. - Query a premium table as that user (allowed) and as a free user (empty).
- Let the accelerated sandbox subscription expire and confirm access ends.
- Restore purchases on a second device signed in to the same account.
- Delete a test account and confirm
on delete cascaderemoves the row.
Common mistakes
-
Trusting the client. An
isProflag in AsyncStorage protects nothing. -
Write policies on
subscriptions. Leave them out so only the service role can write. -
Different user IDs in RevenueCat and Supabase. Always
logInwith the Supabase user ID. - Applying webhook payloads blindly. Re-fetch the subscriber; events can be out of order.
- Sandbox purchases unlocking production. Check the event's environment.
-
Ignoring expiry in policies. Check
expires_at, not just a boolean.
Conclusion
Subscriptions are only as secure as the place that enforces them. Let RevenueCat handle the stores, let a webhook keep a server-only subscriptions table current, and let RLS decide who can read premium data. The SDK still makes the app feel instant, while the database makes it correct.
If you're starting a new app, RapidNative generates Expo and Supabase projects you can export and add this setup to.
Where do you enforce subscriptions today: in the app, on your API or in the database? Share your setup in the comments.
Top comments (1)
One detail worth adding on Step 3: Postgres grants EXECUTE on new public functions to anon and PUBLIC by default, so locking down SECURITY DEFINER helpers with REVOKE EXECUTE FROM PUBLIC, anon keeps the RPC surface clean. Also call resetUser() before identifyUser() on account switches so RevenueCat doesn't alias receipts.