> ## 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: notification inbox with Event Streams

> How the Clean Beans example app builds an in-app notification inbox from Event Streams and keeps email preferences in step with unsubscribes.

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.

A push that is swiped away is gone. Clean Beans keeps a seven-day history inside the app, with an unread count in every screen's header.

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

The inbox lists recent notifications.

The app does not record notifications itself. That would miss anything delivered while the app was closed. OneSignal tells the backend about every push through an **Event Stream**, and the backend keeps the history.

**1. OneSignal sends an event for every push**

An Event Stream posts to a backend function when a push is sent and again when it is clicked.

**2. The function stores or updates a row**

A sent event creates an inbox entry. A click event marks it as read.

**3. The app reads the table**

The inbox screen and the header badge query the user's own rows.

## Configure the Event Stream

**Dashboard setup.** In **Data > Event Streams**, create a stream with:

* **URL:** your function's address.
* **Header:** a shared secret, for example `X-Webhook-Secret`.
* **Events:** `message.push.sent` and `message.push.clicked`.
* **Body:** a Liquid template that shapes the request.

```json Event Stream body theme={null}
{
  "event_kind": "{{ event.kind }}",
  "event_id": "{{ event.id }}",
  "timestamp": {{ event.timestamp }},
  "external_id": "{{ event.external_id }}",
  "message_id": "{{ message.id }}",
  "title": "{{ message.title.en }}",
  "contents": "{{ message.contents.en }}",
  "data": { "type": "{{ message.data.type }}" }
}
```

> [!WARNING]
>
> Reference each `data` key by name, as above. `{{ message.data }}` on its own renders the whole object as a Python-style dict (`{'type': 'kudos'}`), which is not valid JSON, and the function below would reject the request when it parses the body. Title and contents are read with `.en` for the same reason. The inbox only needs `type`. Add a line for any other key your own webhook uses.
>
> A value that contains a double quote also breaks the JSON. Kudos pushes carry text a user typed, so a kudos message with a `"` in it produces a body the function cannot parse, and that push never reaches the inbox.

> [!NOTE]
>
> This stream sends one event for every push delivered to every device, and each event counts toward your plan's message event volume. Select only the events you use.

## Receive the events

The function checks the secret before doing anything else.

```typescript supabase/functions/inbox-webhook/index.ts theme={null}
const secret = req.headers.get('X-Webhook-Secret') ?? '';
if (!INBOX_WEBHOOK_SECRET || secret !== INBOX_WEBHOOK_SECRET) {
  return new Response('Unauthorized', { status: 401 });
}
```

A sent event becomes an inbox row. OneSignal's event ID is the unique key, so an event that is delivered twice does not create two rows.

```typescript supabase/functions/inbox-webhook/index.ts theme={null}
if (event_kind === 'message.push.sent') {
  // ── Create inbox entry ──
  const notifType = (data?.type as string) || 'general';

  // inboxTitle and inboxBody are the title and contents with any Liquid
  // rendered. See "Render Liquid before you store it" below.

  const { error } = await supabase.from('inbox_messages').upsert(
    {
      user_id: profile.id,
      onesignal_event_id: event_id,
      onesignal_message_id: message_id,
      title: inboxTitle || 'Notification',
      body: inboxBody,
      type: notifType,
      data: data || {},
      read: false,
      created_at: payload.timestamp
        ? new Date(payload.timestamp * 1000).toISOString()
        : new Date().toISOString(),
    },
    { onConflict: 'onesignal_event_id' } // dedup
  );
```

A click event marks the matching row as read.

```typescript supabase/functions/inbox-webhook/index.ts theme={null}
const { error, count } = await supabase
  .from('inbox_messages')
  .update({ read: true })
  .eq('onesignal_message_id', message_id)
  .eq('user_id', profile.id);
```

The `data.type` field that routes a tapped push is stored with each row, so the inbox can show the right icon and open the right screen.

## Render Liquid before you store it

The stream reports a message as it was written, before OneSignal personalizes it for each recipient. A push sent by the backend already has its final text. A Journey push does not. One of Clean Beans' Journey messages has this title:

```text Journey push title theme={null}
{{ journey.first_event.properties.room_name }} cleaned ✅
```

The phone shows "Kitchen cleaned ✅". The webhook receives the line above, and the first version of the inbox displayed it exactly like that.

The function now renders the title and body itself before saving them, with a small renderer that handles value lookups and the `default` filter. It gets the values from two places:

* **Tags** are read from the database. The app sets every tag from a value it stores, so the function reads the same values. Passing `{{ user.tags.user_name }}` in the stream body would also work, but a name containing a double quote would make that body invalid JSON.
* **Journey event properties** are not available to the stream. The function rebuilds them from the cleaning session that fired the custom event.

```typescript supabase/functions/inbox-webhook/index.ts theme={null}
if (hasLiquid(inboxTitle) || hasLiquid(inboxBody)) {
  const context = await buildLiquidContext(supabase, payload);
  const renderedTitle = renderLiquid(inboxTitle, context);
  const renderedBody = renderLiquid(inboxBody, context);
  const unresolved = [...renderedTitle.unresolved, ...renderedBody.unresolved];

  if (unresolved.length > 0) {
    // Better no entry than one showing raw template tags
    console.warn(`Inbox: skipped ${message_id} for ${external_id}, unresolved Liquid: ${JSON.stringify(unresolved)}`);
    return jsonResponse({ skipped: true, reason: 'unresolved_liquid', unresolved });
  }

  inboxTitle = renderedTitle.text;
  inboxBody = renderedBody.text;
}
```

> [!WARNING]
>
> If you build an inbox or a log from Event Streams, check what your Journey and template messages look like when they arrive. Any Liquid in them is still Liquid. Either render it yourself, as here, or leave those messages out.

## Show the inbox

Row-level security means each user can only read their own rows, so the app's queries need no filter by user.

```typescript app/inbox.tsx theme={null}
const { data, error } = await supabase
  .from('inbox_messages')
  .select('id, title, body, type, data, read, created_at')
  .order('created_at', { ascending: false })
  .limit(50);
```

```typescript src/components/InboxButton.tsx theme={null}
const fetchCount = async () => {
  const { count, error } = await supabase
    .from('inbox_messages')
    .select('id', { count: 'exact', head: true })
    .eq('read', false);

  if (!cancelled && !error && count !== null) {
    setUnreadCount(count);
  }
};
```

## Keep email preferences in step

The same stream solves a second problem. When someone taps **Unsubscribe** in an email, OneSignal stops emailing them, but the app's own "Weekly Email Summary" switch would still be on. The settings screen would be wrong, and the backend would keep trying to send.

Adding four email events to the stream fixes that. The function treats them all the same way: OneSignal will not email this person again, so the app's preference is switched off to match.

```typescript supabase/functions/inbox-webhook/index.ts theme={null}
const EMAIL_STOP_EVENTS: Record<string, string> = {
  'message.email.unsubscribed': 'unsubscribed',
  'message.email.reported_as_spam': 'reported_as_spam',
  'message.email.bounced': 'bounced',
  'message.email.suppressed': 'suppressed',
};

// ...

const { error: prefErr } = await supabase
  .from('profiles')
  .update({ email_weekly_summary: false })
  .eq('id', profile.id);
```

No change to the stream's body is needed, because the fields the inbox already uses (`event_kind`, `event_id`, `external_id`) are enough.

> [!NOTE]
>
> This keeps the app in step with OneSignal, not the other way round. If someone switches the email back on in the app, their OneSignal subscription is still unsubscribed. Re-subscribing them takes a call from your backend to OneSignal's subscription API.

> [!TIP]
>
> The same Event Stream pattern can keep your own systems in step with anything OneSignal knows: email opens, in-app message clicks, SMS delivery, and more.

> [card] [Event Streams](https://documentation.onesignal.com/docs/en/event-streams.md)
>
> Set up a stream and choose events.

> [card] [Event Stream data](https://documentation.onesignal.com/docs/en/event-streams-data.md)
>
> Every field available in the body template.


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