> ## 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: SDK setup and user identity

> How the Clean Beans example app installs the OneSignal SDK in Expo, ties each device to a user with an External ID, and adds email.

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.

Everything else depends on four things being right: the SDK is installed, it starts when the app starts, each device is tied to a user, and people can control what they receive.

## Install with the Expo plugin

The `onesignal-expo-plugin` configures the native iOS and Android projects at build time. It adds the push capability, the App Group, and the Notification Service Extension that OneSignal needs for images, badges, and confirmed delivery.

```json app.json theme={null}
{
  "expo": {
    "plugins": [
      ["onesignal-expo-plugin", { "mode": "production" }],
      "expo-router",
      "./plugins/withLiveActivityWidget"
    ],
    "ios": {
      "bundleIdentifier": "com.onesignal.cleaningapp",
      "infoPlist": {
        "UIBackgroundModes": ["remote-notification"],
        "NSSupportsLiveActivities": true
      },
      "entitlements": {
        "aps-environment": "production",
        "com.apple.security.application-groups": [
          "group.com.onesignal.cleaningapp.onesignal"
        ]
      }
    }
  }
}
```

## Initialize once, at the root

Clean Beans initializes OneSignal in its root layout, so it runs once on every launch before any screen appears.

```typescript app/_layout.tsx theme={null}
// Verbose logging is for debugging during the beta. Remove it, or lower
// the level, before a public release.
OneSignal.Debug.setLogLevel(LogLevel.Verbose);
OneSignal.initialize('YOUR_ONESIGNAL_APP_ID');
OneSignal.Notifications.requestPermission(true);
```

> [!TIP]
>
> Asking for permission on first launch is the simplest approach. To explain the benefit first, show an in-app message before the system prompt. Clean Beans has one ready: see [Push permission pre-prompt](https://documentation.onesignal.com/docs/en/example-full-integration-in-app-messages.md#push-permission-pre-prompt).

## Tie each device to a user

When someone signs in, the app passes their Supabase user ID to `OneSignal.login()`. That ID becomes the External ID. When they sign out, `logout()` detaches the device so the next person to sign in does not inherit their messages.

```typescript app/_layout.tsx theme={null}
// Link OneSignal identity to authenticated user and sync timezone
//
// Wait until the saved session has been restored. On a cold start `user`
// is null for a moment while it loads; calling logout() then, followed by
// login() a moment later, can leave this device's push subscription on an
// anonymous OneSignal user, so pushes sent to the External ID never reach
// the phone. logout() is only called on a real sign-out.
const wasSignedIn = useRef(false);
useEffect(() => {
  if (loading) return;

  if (user) {
    wasSignedIn.current = true;
    OneSignal.login(user.id);
    syncDeviceTimezone();
    // Add email subscription and sync data tags to OneSignal
    if (user.email) syncOneSignalEmail(user.email);
    // Add the SMS subscription if the user has a verified phone number
    syncOneSignalSms();
    syncOneSignalTags();
  } else if (wasSignedIn.current) {
    wasSignedIn.current = false;
    OneSignal.logout();
  }
}, [user, loading]);
```

> [!WARNING]
>
> Wait for the saved session to load before calling either method. On a cold start the signed-in user is briefly unknown. If the app calls `logout()` at that moment and `login()` a moment later, the device's push subscription can be left on an anonymous user, and pushes addressed to the External ID stop reaching the phone. Call `logout()` only when someone really signs out.

This one call is what makes every backend send in this guide possible. A function that knows a user's database ID can message them without knowing anything about their devices.

## Add the email channel

The app already knows each user's email address from sign-up, so it registers it as an email subscription at sign-in. OneSignal ignores repeat calls with the same address.

```typescript src/lib/onesignalSync.ts theme={null}
export function syncOneSignalEmail(email: string): void {
  try {
    if (!email) return;
    OneSignal.User.addEmail(email);
    console.log('[onesignalSync] Email subscription added');
  } catch (e) {
    console.warn('[onesignalSync] syncOneSignalEmail error:', e);
  }
}
```

SMS is added the same way with `addSms()`, but only after the number has been verified. See [SMS: verification codes and invitations](https://documentation.onesignal.com/docs/en/example-full-integration-sms.md).

## Let people control what they get

The notification settings screen has a master switch and one switch per message type.

![The notification settings screen with a master toggle and per-type toggles](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-notifications.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=57fef32f8987a51e7bdf8c40a6273087)

Notification settings: a master switch, per-type switches, and the daily reminder time.

The master switch calls `optOut()` and `optIn()` on the push subscription, so OneSignal stops and resumes delivery to that device.

```typescript app/notification-settings.tsx theme={null}
const handlePushMasterToggle = async (enabled: boolean) => {
  try {
    if (enabled) {
      OneSignal.User.pushSubscription.optIn();
    } else {
      OneSignal.User.pushSubscription.optOut();
    }
  } catch (e) {
    console.warn('OneSignal subscription toggle failed:', e);
  }
  save({ ...prefs, pushEnabled: enabled });
};
```

Every switch is also saved to the user's profile row. The backend reads these columns before it sends anything, which is how per-type preferences are enforced.

```typescript src/lib/database.ts theme={null}
  const { error } = await supabase
    .from('profiles')
    .update({
      notifications_enabled: prefs.pushEnabled,
      push_daily_reminders: prefs.pushDailyReminders,
      push_streak_reminders: prefs.pushStreakReminders,
      push_cleaning_done: prefs.pushCleaningDone,
      push_leaderboard_updates: prefs.pushLeaderboardUpdates,
      push_upcoming_cleaning: prefs.pushUpcomingCleaning,
      push_overdue_reminders: prefs.pushOverdueReminders,
      email_weekly_summary: prefs.emailWeeklySummary,
      notification_hour: prefs.notificationHour,
      timezone: prefs.timezone,
    })
    .eq('id', user.id);
```

> [!NOTE]
>
> Storing preferences in your own database, and checking them before each send, keeps the logic in one place. The alternative is to store them as tags and filter by tag in OneSignal. That works well when you send to segments. Clean Beans sends to specific users, so checking the database is simpler.

> [card] [Mobile SDK reference](https://documentation.onesignal.com/docs/en/mobile-sdk-reference.md)
>
> Every client method used in this guide.

> [card] [Users and External IDs](https://documentation.onesignal.com/docs/en/users.md)
>
> How identity links subscriptions across channels and devices.


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