DEV Community

Cover image for Sending Push Notifications from Supabase to an Expo App: Database Webhooks, Edge Functions and Receipts
Jules Sarah
Jules Sarah

Posted on

Sending Push Notifications from Supabase to an Expo App: Database Webhooks, Edge Functions and Receipts

most push notification tutorials stop once the app has a token. The other half lives on the server: store tokens in a table protected by RLS, fire a database webhook when something happens (a new message, an order status change), send the notification from a Supabase Edge Function through Expo's push API in batches, then check push receipts later and delete tokens for uninstalled apps. This guide builds that pipeline end to end.

Getting an Expo push token on the device is well documented. What usually isn't: how a real event in your database turns into a notification on the right person's phone, reliably, without spamming and without keeping dead tokens forever.

The pipeline

INSERT into public.messages
        │  database webhook
        ▼
Edge Function "notify-message"
        │  look up recipient's tokens (service role)
        │  POST batches to Expo push API
        ▼
Expo Push Service ──► APNs / FCM ──► recipient's phone
        │
        └─ tickets saved ──► scheduled job checks receipts ──► delete dead tokens
Enter fullscreen mode Exit fullscreen mode

Step 1: A table for push tokens

One user can have several devices, so store one row per token:

create table public.push_tokens (
  token text primary key,
  user_id uuid not null references auth.users (id) on delete cascade,
  platform text,
  updated_at timestamptz not null default now()
);

create index push_tokens_user_id_idx on public.push_tokens (user_id);

alter table public.push_tokens enable row level security;

create policy "Users manage own tokens"
  on public.push_tokens for all to authenticated
  using ( (select auth.uid()) = user_id )
  with check ( (select auth.uid()) = user_id );
Enter fullscreen mode Exit fullscreen mode

The token is the primary key, so if a phone changes hands (a new user signs in on the same device), an upsert moves the token to the new user instead of notifying both.

Step 2: Save the token from the app

After getting permission and the Expo push token on the device (with expo-notifications), upsert it:

import { Platform } from 'react-native';
import { supabase } from '@/lib/supabase';

export async function saveToken(token: string, userId: string) {
  await supabase.from('push_tokens').upsert({
    token,
    user_id: userId,
    platform: Platform.OS,
    updated_at: new Date().toISOString(),
  });
}
Enter fullscreen mode Exit fullscreen mode

On sign-out, delete the device's token so a signed-out phone stops receiving that user's notifications:

await supabase.from('push_tokens').delete().eq('token', token);
Enter fullscreen mode Exit fullscreen mode

Step 3: The event that triggers a notification

We'll notify users about new chat messages:

create table public.messages (
  id bigint generated always as identity primary key,
  conversation_id uuid not null,
  sender_id uuid not null references auth.users (id),
  recipient_id uuid not null references auth.users (id),
  body text not null,
  created_at timestamptz not null default now()
);
Enter fullscreen mode Exit fullscreen mode

Any table works: orders changing to "ready", a booking reminder row, a new follower.

Step 4: Create the Edge Function

// supabase/functions/notify-message/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')!
);

const EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send';

Deno.serve(async (req) => {
  // Shared secret configured on the webhook
  if (req.headers.get('x-webhook-secret') !== Deno.env.get('WEBHOOK_SECRET')) {
    return new Response('Unauthorized', { status: 401 });
  }

  const payload = await req.json(); // { type, table, schema, record, old_record }
  if (payload.type !== 'INSERT') return new Response('ignored');
  const message = payload.record;

  // Don't notify people about their own messages
  if (message.sender_id === message.recipient_id) return new Response('ignored');

  const { data: tokens } = await admin
    .from('push_tokens')
    .select('token')
    .eq('user_id', message.recipient_id);
  if (!tokens?.length) return new Response('no tokens');

  const messages = tokens.map((t) => ({
    to: t.token,
    title: 'New message',
    body: message.body.slice(0, 120),
    sound: 'default',
    data: { url: `/conversations/${message.conversation_id}` },
  }));

  // Expo accepts up to 100 messages per request
  const tickets = [];
  for (let i = 0; i < messages.length; i += 100) {
    const res = await fetch(EXPO_PUSH_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(messages.slice(i, i + 100)),
    });
    const json = await res.json();
    tickets.push(...(json.data ?? []));
  }

  // Save ticket IDs so a scheduled job can check receipts later
  const rows = tickets
    .map((ticket, i) => ({ ticket, token: messages[i].to }))
    .filter(({ ticket }) => ticket.status === 'ok')
    .map(({ ticket, token }) => ({ ticket_id: ticket.id, token }));
  if (rows.length) await admin.from('push_tickets').insert(rows);

  return new Response('sent');
});
Enter fullscreen mode Exit fullscreen mode

A few details worth keeping:

  • Truncate the body. Long messages get cut off by the OS anyway, and you don't want to send whole private conversations through push.
  • Put a route in data. The app can open the right screen when the notification is tapped.
  • If you enable Expo's enhanced push security, add your Expo access token as an Authorization: Bearer header on the request.
  • Respect preferences. Before sending, check a notification_settings table so users who muted message notifications don't get them.

Step 5: Connect the database webhook

In the Supabase dashboard, open Database → Webhooks and create a webhook:

  • Table: public.messages
  • Events: Insert
  • Type: Supabase Edge Function (or HTTP request to its URL)
  • Header: x-webhook-secret with the same value as your function's WEBHOOK_SECRET

Deploy the function so it doesn't require a user JWT, since the database calls it directly; the shared secret protects it. Now every new message row triggers the function.

Step 6: Check receipts and remove dead tokens

A ticket with status "ok" only means Expo accepted the message. Whether Apple or Google delivered it shows up later in a receipt. The receipt also tells you when a token is dead, typically with the error DeviceNotRegistered, meaning the app was uninstalled.

Store tickets:

create table public.push_tickets (
  ticket_id text primary key,
  token text not null,
  created_at timestamptz not null default now()
);
alter table public.push_tickets enable row level security;
-- No policies: only the service role reads and writes this table
Enter fullscreen mode Exit fullscreen mode

Then a second function checks receipts for tickets that are at least 15 minutes old:

// supabase/functions/check-receipts/index.ts (core logic)
const { data: pending } = await admin
  .from('push_tickets')
  .select('ticket_id, token')
  .lt('created_at', new Date(Date.now() - 15 * 60 * 1000).toISOString())
  .limit(1000);

const ids = (pending ?? []).map((p) => p.ticket_id);
if (ids.length) {
  const res = await fetch('https://exp.host/--/api/v2/push/getReceipts', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ids }),
  });
  const { data: receipts } = await res.json();

  for (const p of pending ?? []) {
    const receipt = receipts?.[p.ticket_id];
    if (receipt?.status === 'error' && receipt.details?.error === 'DeviceNotRegistered') {
      await admin.from('push_tokens').delete().eq('token', p.token);
    }
  }
  await admin.from('push_tickets').delete().in('ticket_id', ids);
}
Enter fullscreen mode Exit fullscreen mode

Run it on a schedule, for example every 30 minutes, with Supabase's cron scheduling calling the function. Your token table stays clean, and you stop sending to phones that no longer have the app.

Step 7: Test the pipeline

  1. Sign in as user A on a real device (push doesn't work on most simulators) and confirm a row appears in push_tokens.
  2. As user B, insert a message to user A.
  3. Check the function logs for "sent" and the notification on A's phone.
  4. Tap the notification and confirm it opens the conversation.
  5. Uninstall the app on a test device, send another message, wait for the receipt job and confirm the token row is deleted.

Common mistakes

  • No RLS on the token table, letting anyone read every user's push tokens.
  • Sending from the client. Anyone could send notifications to anyone. Always send from the server.
  • Notifying the sender of their own action.
  • Never cleaning up tokens, so you keep sending to uninstalled apps.
  • One request per notification instead of batches of up to 100.
  • No user preferences, which leads people to disable notifications entirely.

Conclusion

The device side of push notifications is only half the job. A database webhook, an Edge Function that sends batches through Expo's push API, a protected token table and a receipt job that removes dead tokens give you a pipeline that's reliable, secure and quiet when it should be.

If you're starting a new app, RapidNative generates Expo and Supabase projects you can export and add this pipeline to.

What triggers push notifications in your app: database events, a backend queue or something else? Share your setup in the comments.

Top comments (0)