> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.onesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Example app: sending push from your backend

> Six push notifications sent from Supabase Edge Functions with the Create message API, on a schedule, from the app, and from a database trigger.

This page is part of [Example app: a full OneSignal integration](https://documentation.onesignal.com/docs/en/example-full-integration-overview.md), which follows one real app from end to end. The app is **Clean Beans**, a cleaning rota for shared homes, built with Expo (React Native) and a Supabase backend.

Most Clean Beans notifications are sent by the backend, because they depend on a schedule or on something another person did. All of them call the same endpoint, [Create message](https://documentation.onesignal.com/reference/create-message.md), and target people by External ID.

| Push | Sent when | Trigger |
| - | - | - |
| Daily digest | The user's chosen hour, if tasks are due | Hourly schedule |
| Overdue reminder | Six hours after the digest, if tasks are still overdue | Hourly schedule |
| Cleaning reminder | One hour before the user's cleaning window | Hourly schedule |
| Session completed | A housemate finishes cleaning | Call from the app |
| Kudos | A housemate sends kudos | Call from the app |
| Join approved | An admin approves a join request | Database trigger |

![Clean Beans push notifications](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-push-examples.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=f26bc81be159fba77a9873e119ccb19e)

An example of some of the pushes that Clean Beans sends.

## Scheduled sends that respect time zones

People choose the hour they want their daily reminder. Clean Beans does not schedule one job per user. It runs one job every hour and asks, "for whom is it that hour right now?"

**1. A database schedule calls a function every hour**

`pg_cron` makes an HTTP request to a Supabase Edge Function. The service key it needs is read from Supabase Vault, so it never appears in the SQL.

**2. The function finds the users whose local hour matches**

It loads everyone who has that reminder switched on, converts the current time to each user's time zone, and keeps the ones whose chosen hour is now.

**3. It checks there is something to say**

A user with nothing due gets no push.

**4. It calls OneSignal once per user**

Each push has its own content, so each is a separate request.

The schedule:

```sql supabase/migrations/006_cron_daily_digest.sql theme={null}
select cron.schedule(
  'send-daily-digest',          -- job name
  '0 * * * *',                  -- every hour at :00
  $$
  select
    net.http_post(
      url := 'https://YOUR_PROJECT_REF.supabase.co/functions/v1/send-daily-digest',
      headers := jsonb_build_object(
        'Content-Type', 'application/json',
        'Authorization', 'Bearer ' || (select decrypted_secret from vault.decrypted_secrets where name = 'service_role_key')
      ),
      body := '{}'::jsonb
    );
  $$
);
```

The time zone match:

```typescript supabase/functions/send-daily-digest/index.ts theme={null}
for (const profile of profiles) {
  try {
    // Get current hour in user's timezone
    const localHour = parseInt(
      now.toLocaleString('en-US', {
        timeZone: profile.timezone || 'UTC',
        hour: 'numeric',
        hour12: false,
      }),
      10
    );

    if (localHour === profile.notification_hour) {
      eligibleUsers.push({
        id: profile.id,
        householdId: profile.household_id,
        localDate: localDate(now, profile.timezone || 'UTC'),
      });
    }
  } catch {
    // Invalid timezone — skip this user
    console.warn(`Invalid timezone for user ${profile.id}: ${profile.timezone}`);
  }
}
```

The send:

```typescript supabase/functions/send-daily-digest/index.ts theme={null}
const onesignalPayload = {
  app_id: ONESIGNAL_APP_ID,
  // One digest per user per local day: a retried or duplicated cron
  // run reuses this key and OneSignal will not send it twice.
  idempotency_key: await idempotencyKey('daily_digest', digest.userId, digest.localDate),
  include_aliases: {
    external_id: [digest.userId],
  },
  target_channel: 'push',
  ...DELIVERY.daily_digest,
  headings: { en: heading },
  contents: { en: body },
  url: 'cleaning-rota:///(tabs)/clean',
  // App icon badge = number of tasks due. The OneSignal SDK clears the
  // badge automatically the next time the app is opened.
  ios_badgeType: 'SetTo',
  ios_badgeCount: digest.tasks.length,
  // Action buttons, revealed by expanding the notification
  buttons: TASK_BUTTONS,
  data: { type: 'daily_digest', taskCount: String(digest.tasks.length) },
};

const res = await fetch('https://api.onesignal.com/notifications', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Key ${ONESIGNAL_REST_API_KEY}`,
  },
  body: JSON.stringify(onesignalPayload),
});
```

The `...DELIVERY.daily_digest`, `idempotency_key`, and badge fields are explained in [Reliable, well-behaved push](https://documentation.onesignal.com/docs/en/example-full-integration-reliable-push.md). The `data.type` field is how the app knows which screen to open when the push is tapped. See [Deep links and notification clicks](https://documentation.onesignal.com/docs/en/example-full-integration-deep-links.md).

The heading and body are built from the tasks, so the push says something specific.

```typescript supabase/functions/send-daily-digest/index.ts theme={null}
function buildDigestContent(tasks: TaskRow[]): { heading: string; body: string } {
  const count = tasks.length;
  const heading = count === 1
    ? '1 cleaning task due today'
    : `${count} cleaning tasks due today`;

  // Collect unique room names
  const rooms = [...new Set(tasks.map(t => t.room_name))];

  let body: string;
  if (rooms.length === 1) {
    body = `Your ${rooms[0]} needs some attention!`;
  } else if (rooms.length === 2) {
    body = `Your ${rooms[0]} and ${rooms[1]} need some attention!`;
  } else {
    const last = rooms.pop()!;
    body = `Your ${rooms.join(', ')}, and ${last} need some attention!`;
  }

  return { heading, body };
}
```

## The overdue reminder: a second, different nudge

The overdue reminder reuses the same pattern with two changes. It fires six hours after the user's digest hour, and it only counts tasks that are strictly past due.

```typescript supabase/functions/send-overdue-reminders/index.ts theme={null}
// Overdue hour wraps around midnight
const overdueHour = (profile.notification_hour + OVERDUE_OFFSET_HOURS) % 24;

if (localHour === overdueHour) {
  eligibleUsers.push({
    id: profile.id,
    householdId: profile.household_id,
    localDate: localDate(now, profile.timezone || 'UTC'),
  });
}
```

Its job runs at half past the hour, so it never competes with the digest job at the top of the hour. The copy is different too. A second reminder that repeats the first is easy to ignore.

```typescript supabase/functions/send-overdue-reminders/index.ts theme={null}
function buildOverdueContent(tasks: TaskRow[]): { heading: string; body: string } {
  const count = tasks.length;
  const heading = count === 1
    ? '1 overdue task still waiting'
    : `${count} overdue tasks still waiting`;

  const rooms = [...new Set(tasks.map((t) => t.room_name))];

  let body: string;
  if (rooms.length === 1) {
    body = `Your ${rooms[0]} still needs some love today!`;
  } else if (rooms.length === 2) {
    body = `Your ${rooms[0]} and ${rooms[1]} still need some love today!`;
  } else {
    const last = rooms.pop()!;
    body = `Your ${rooms.join(', ')}, and ${last} still need some love today!`;
  }

  return { heading, body };
}
```

## The cleaning reminder: one request for many people

The cleaning reminder says the same thing to everyone, so it does not need one request per person. The function collects every eligible user ID and sends them in batches.

```typescript supabase/functions/send-cleaning-reminder/index.ts theme={null}
const batchSize = 2000;
for (let i = 0; i < eligibleUserIds.length; i += batchSize) {
  const batch = eligibleUserIds.slice(i, i + batchSize);

  // One reminder per batch of recipients per hourly cron slot: a retried
  // or duplicated run in the same hour reuses this key and OneSignal
  // will not send it twice.
  const batchKey = await idempotencyKey(
    'upcoming_cleaning',
    utcHourSlot(now),
    [...batch].sort().join(','),
  );

  const onesignalPayload = {
    app_id: ONESIGNAL_APP_ID,
    idempotency_key: batchKey,
    include_aliases: {
      external_id: batch,
    },
    target_channel: 'push',
    ...DELIVERY.upcoming_cleaning,
    headings: { en: 'Cleaning time in 1 hour' },
    contents: {
      en: 'Your cleaning window starts soon. Ready to get things sparkling?',
    },
    url: 'cleaning-rota:///(tabs)/clean',
    data: { type: 'upcoming_cleaning' },
  };
```

> [!TIP]
>
> Send one request per person when the content differs. Send one request for many people when it is identical. Fewer requests means fewer things to fail and less to stay inside rate limits.

## Session completed: a push triggered from the app

When someone finishes a cleaning session, the rest of the household hears about it. The app cannot send that push itself, because it must not hold an API key. It calls a backend function and the function sends the push.

```typescript src/lib/database.ts theme={null}
const { error } = await supabase.functions.invoke('session-completed', {
  body: {
    householdId,
    roomName: params.roomName,
    tasksCompleted: params.tasksCompleted,
    estimatedMins: params.estimatedMins,
  },
});
```

The request says what was cleaned, but not who cleaned it. The function reads who is calling from their sign-in token, checks they are an active member of the household, and takes their name and avatar from their profile. See [Check who is calling](#check-who-is-calling).

It then finds the other members of the household and removes anyone who has this type of push switched off.

```typescript supabase/functions/session-completed/index.ts theme={null}
// ── 1. Look up other active household members ──

const { data: members, error: memberErr } = await supabase
  .from('household_members')
  .select('user_id')
  .eq('household_id', householdId)
  .eq('status', 'active')
  .neq('user_id', userId);

    // ...

const { data: profiles, error: profileErr } = await supabase
  .from('profiles')
  .select('id, notifications_enabled, push_cleaning_done')
  .in('id', recipientIds)
  .eq('notifications_enabled', true)
  .eq('push_cleaning_done', true);
```

It sends one push to all of them. The sender's bean avatar is attached as an image, using a different field for each platform.

```typescript supabase/functions/session-completed/index.ts theme={null}
const onesignalPayload: Record<string, unknown> = {
  app_id: ONESIGNAL_APP_ID,
  include_aliases: {
    external_id: enabledIds,
  },
  target_channel: 'push',
  ...DELIVERY.session_completed,
  headings: { en: heading },
  contents: { en: body },
  url: 'cleaning-rota:///activity',
  data: {
    type: 'session_completed',
    roomName,
    userName,
    tasksCompleted: String(tasksCompleted),
    // Who cleaned: lets the "Send kudos" button reply to the right person
    ...(isRealUser ? { cleanerId: userId } : {}),
  },
  // "Send kudos" needs a real person to send to
  ...(isRealUser ? { buttons: SESSION_BUTTONS } : {}),
};

// Attach avatar image for rich push notifications
if (avatarImageUrl) {
  onesignalPayload.big_picture = avatarImageUrl;          // Android
  onesignalPayload.ios_attachments = { avatar: avatarImageUrl }; // iOS
}
```

![An expanded push notification showing a bean avatar image](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-rich-push.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=07c38920b20cb73093805ca9961841e3)

A session-completed push, expanded to show the sender's avatar.

## Kudos: one person to another

Kudos work the same way, with a single recipient. On the activity screen, a member taps **Send Kudos** on a housemate's session, picks a message, and the app calls the `send-kudos` function.

![The kudos bottom sheet with preset messages](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-kudos.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=83ec608d61e91c74f16bcb65d8757927)

Choosing a kudos message for a housemate's cleaning session.

```typescript supabase/functions/send-kudos/index.ts theme={null}
const heading = `Kudos from ${senderName}!`;
const body = message;

    // ...

const onesignalPayload: Record<string, unknown> = {
  app_id: ONESIGNAL_APP_ID,
  include_aliases: {
    external_id: [recipientUserId],
  },
  target_channel: 'push',
  ...DELIVERY.kudos,
  headings: { en: heading },
  contents: { en: body },
  url: 'cleaning-rota:///activity',
  data: {
    type: 'kudos',
    senderName,
    roomName: roomName || '',
  },
};
```

## Join approved: a push triggered by the database

Someone who asks to join a household waits for an admin to approve them. When that happens, their membership row changes from `pending` to `active`. A database trigger on that change calls a function, and the function tells them they are in.

Putting the trigger in the database means the push is sent however the approval happens, and the app needs no code for it.

```sql supabase/migrations/027_join_approved_trigger.sql theme={null}
create trigger trg_notify_join_approved
  after update of status on public.household_members
  for each row
  when (old.status = 'pending' and new.status = 'active')
  execute function public.notify_join_approved();
```

The function does not trust what it is told. It reads the membership again and only sends if the approval is real and recent.

```typescript supabase/functions/join-approved/index.ts theme={null}
// ── 1. Confirm the membership really was approved, and recently ──

const { data: membership, error: memberErr } = await supabase
  .from('household_members')
  .select('status, joined_at, households(name)')
  .eq('user_id', userId)
  .eq('household_id', householdId)
  .maybeSingle();

if (memberErr) throw memberErr;

if (!membership || membership.status !== 'active' || !membership.joined_at) {
  return jsonResponse({ sent: 0, message: 'No active membership found' });
}

const joinedAt = new Date(membership.joined_at).getTime();
if (Date.now() - joinedAt > RECENT_APPROVAL_MS) {
  return jsonResponse({ sent: 0, message: 'Membership was not approved recently' });
}
```

> [!WARNING]
>
> A function that sends messages on request is something other people can try to call. Check the facts in your own database before sending, as this one does, and never accept message content or recipients from a caller you have not verified.

## Check who is calling

Supabase verifies that a request to an edge function carries a valid token, but a signed-in user's token is as valid as the scheduler's. Without a further check, any user could trigger the daily digest for everyone, or send a push in someone else's name. Each function therefore decides for itself who is allowed to call it.

| Functions | Who may call | Check |
| - | - | - |
| Scheduled sends and the database trigger | The scheduler only | The token must be the service role key |
| Session completed, kudos | A signed-in user, as themselves | The sender comes from the token, never from the request body |

The scheduled functions start with one line:

```typescript supabase/functions/send-daily-digest/index.ts theme={null}
// Only the scheduler (service role) may run this
const denied = requireServiceRole(req);
if (denied) return denied;
```

```typescript supabase/functions/_shared/auth.ts theme={null}
export function isServiceRoleRequest(req: Request): boolean {
  const token = bearerToken(req);
  if (!token) return false;
  if (token === Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')) return true;

  try {
    const part = token.split('.')[1] ?? '';
    const base64 = part.replace(/-/g, '+').replace(/_/g, '/');
    const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
    const claims = JSON.parse(atob(padded));
    return claims?.role === 'service_role';
  } catch {
    return false;
  }
}
```

> [!WARNING]
>
> The role check relies on Supabase having already verified the token's signature. Deploy these functions with JWT verification on, which is the default. Never deploy them with `--no-verify-jwt`.

Functions called from the app identify the sender from the token, then check that the sender is allowed to reach the recipient. Kudos can only go to someone who shares a household with the sender, and the name shown in the push is read from the sender's profile.

```typescript supabase/functions/send-kudos/index.ts theme={null}
const caller = await authenticateUser(req, supabase);
if (caller instanceof Response) return caller;

// ...

// Sender and recipient must be active members of the same household
const { data: memberships, error: memberErr } = await supabase
  .from('household_members')
  .select('user_id, household_id')
  .in('user_id', [caller.id, recipientUserId])
  .eq('status', 'active');

if (memberErr) throw memberErr;

const callerHouseholds = new Set(
  (memberships ?? []).filter((m) => m.user_id === caller.id).map((m) => m.household_id),
);
const sharesHousehold = (memberships ?? []).some(
  (m) => m.user_id === recipientUserId && callerHouseholds.has(m.household_id),
);

if (!sharesHousehold) {
  return jsonResponse({ error: 'forbidden', message: 'You can only send kudos to members of your household.' }, 403);
}
```

> [card] [Create message API](https://documentation.onesignal.com/reference/create-message.md)
>
> Targeting, content, and scheduling for every channel.

> [card] [Rich media](https://documentation.onesignal.com/docs/en/rich-media.md)
>
> Images in push notifications on each platform.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.