Skip to main content

React Native SDK

@opennotification/react-native covers iOS and Android from one JavaScript API, and the whole native side ships inside the package: no @react-native-firebase/*, no Notifee, no AsyncStorage. iOS talks to APNs directly through a native module — no Firebase iOS SDK. Android embeds the Kotlin SDK over Firebase Messaging and draws every notification itself; Firebase Messaging comes in through Gradle, not npm.

1 Install​

bun add @opennotification/react-native

Then pick one: the Expo plugin or the manual setup.

2 Initialise​

import { OpenNotification } from "@opennotification/react-native";

OpenNotification.init({
endpoint: "https://push.example.com",
appKey: "pk_live_…",
autoRegister: false, // true: ask for permission during init
androidSmallIcon: "ic_notification", // drawable name, monochrome
});

init needs no await: it returns a promise, but every call made while it is still loading queues behind it, so it can be a bare statement at the top of your app. Await it only when you want the client object or the autoRegister result.

init wires the native listeners and, on Android, gets the FCM token and registers immediately (permission is not needed to receive a token). On iOS nothing is sent until permission is granted. There is no background handler to register in index.js: drawing and tracking are native, so FCM waking the process with no JavaScript in it is fine.

3 Permission, identity, tags, opens​

Ask for permission where the user understands why — after they turn on a feature that needs it, not on first launch:

const result = await OpenNotification.requestPermission();
if (!result.ok) console.warn(result.error.code); // permission_denied | no_token | api_error | network_error

Listeners are registered once, wherever your navigation is ready:

const off = OpenNotification.onOpen((message) => {
navigate(message.data.screen ?? "Home", message.data); // message.url, message.actionId also available
});
OpenNotification.onReceive((message) => {
if (message.silent) sync(message.data); // background push: nothing was shown, data is the message
});

The rest belongs to moments in your app, not to one block:

OpenNotification.login("user_123"); // your sign-in succeeded
OpenNotification.setTags({ plan: "platinum", streak: 42 });
OpenNotification.setEmail("[email protected]"); // null removes
OpenNotification.setPhone("+905551234567"); // E.164, null removes

OpenNotification.logout(); // your sign-out
OpenNotification.unsubscribe(); // they turned notifications off in your settings

None of these throw, so there is nothing to try. They return Promise<Result<…>>, and await is only worth writing when you are going to read it:

const saved = await OpenNotification.setTags({ plan: "platinum" });
if (!saved.ok) retryLater(); // { code: "network_error" | "api_error" | "not_subscribed", … }

Fire and forget is fine otherwise — the call is queued the moment you make it, and a dropped tag write is not worth blocking a screen for.

onOpen fires for a cold launch too: the press that started the app is held until a listener exists, so it reaches you whether you register before or after init settles. Only the first listener receives it, once.

Sessions are counted for you: start() listens to AppState and pings /session on every return to the foreground; the server applies the 30-minute idle rule, so nothing is double-counted. Silent pushes reach onReceive with message.silent === true — on iOS forward application(_:didReceiveRemoteNotification:fetchCompletionHandler:) to OpenNotification.didReceiveBackground(userInfo:) (see the AppDelegate below) and enable the Remote notifications background mode.

await OpenNotification.permissionStatus() returns granted | denied | provisional | not_determined; OpenNotification.register() re-sends the registration explicitly.

removeTags(keys) and setLanguage(code) are on the facade as well.

Foreground, the notification centre, badge, outcomes​

// Hide the open conversation's pushes while it is on screen (onReceive still fires).
OpenNotification.setForegroundPresentation({ hideWhen: [{ type: "chat", senderId: "42" }] });
OpenNotification.setForegroundPresentation({}); // back to showing everything
OpenNotification.setForegroundPresentation({ show: false }); // nothing while the app is open

OpenNotification.removeNotification("chat_42"); // the push sent with collapseId "chat_42"
OpenNotification.removeGroup("chat_42"); // everything sent with presentation.threadId "chat_42"
OpenNotification.clearAll();

OpenNotification.setBadgeCount(3); // iOS; Android launchers count the shade themselves
OpenNotification.clearBadge();

OpenNotification.onPermissionChange((status) => {}); // e.g. turned off in Settings
OpenNotification.onSubscriptionChange(({ previous, current }) => {});

await OpenNotification.sendOutcome("purchase", 9.99);
  • Foreground rules are decided natively when the push lands — iOS gives the delegate a short deadline, too short for a round trip to JavaScript. A rule matches when every key it names equals the push's data value. On iOS this needs the AppDelegate to call OpenNotification.presentationOptions(for:) (below).
  • collapseId replaces the notification on screen on both platforms (Android: the SDK posts every push with the same collapse id under one notification id). On Android, pushes with a presentation.threadId are bundled under a summary from the second one on.
  • Badge: clearBadgeOnOpen (default true) zeroes the iOS badge on every foreground, as OneSignal does. presentation.badgeIncrement adds to the current badge; the service extension keeps the running count in an App Group, so add the same OpenNotificationAppGroup string to the app's and the extension's Info.plist.
  • Permission changes are noticed on each foreground; going from on to off (or back) also sets the device's optedIn on the server.
  • Outcomes: if the user opened a notification within outcomeWindowMinutes (default 1440), the outcome is credited to that campaign and shows on its report; otherwise it is stored unattributed. Names are ^[a-z0-9_-]{1,64}$.

Device facts​

Registration and every session ping also carry what OneSignal used to collect, so an imported audience and a native one look the same in segments and reports: hardware model (iPhone16,1, samsung SM-A566E), OS and app version, language, timezone, country, rooted / jailbroken (the usual heuristics — a segment facet, not a security check), foreground time (usageDuration, banked when the app goes to the background and sent with the next ping) and the last known position — only when your app already holds location permission. The SDK never asks for location and sends no location key without it; the client IP is recorded server side from the request.

setEmail / setPhone store contact channels on the user, like tags. Nothing is delivered on them; they exist so a OneSignal import loses nothing and a segment can still ask "has an email". Phone numbers are E.164; null removes the value.

Expo config plugin​

{
"expo": {
"ios": { "bundleIdentifier": "com.acme.app" },
"android": { "googleServicesFile": "./google-services.json" },
"plugins": [
["@opennotification/react-native", {
"endpoint": "https://push.example.com",
"androidSmallIconPath": "./assets/ic_notification.png"
}]
]
}
}

npx expo prebuild (or an EAS build) then applies everything the manual setup below lists:

PlatformWhat the plugin does
iOSaps-environment entitlement, remote-notification background mode, the four AppDelegate callbacks, a NotificationService extension target with OpenNotificationApiUrl = endpoint in its Info.plist.
AndroidPOST_NOTIFICATIONS permission, copies androidSmallIconPath to res/drawable/ic_notification.png. google-services.json and the Gradle plugin come from Expo's own android.googleServicesFile.
OptionDefault
endpoint—API base URL for the extension.
iosServiceExtensiontrueSet false to skip the extension (no delivered on iOS then).
iosServiceExtensionNameNotificationServiceTarget name; bundle id is <bundleIdentifier>.<name>.
iosDeploymentTargetapp's
iosApsEnvironmentdevelopmentEAS sets the right one at build time.
androidSmallIconPath—Monochrome PNG, white on transparent.
androidSmallIconic_notificationDrawable name for the PNG above.

Still yours: the extension's App ID and profile (com.acme.app.NotificationService) — or let EAS manage it via extra.eas.build.experimental.ios.appExtensions — and the .p8 upload (iOS platform setup). The plugin patches the Swift AppDelegate of Expo SDK 53+, and it does not coexist with expo-notifications, which claims the same notification delegate.

Manual setup (bare React Native)​

Android​

1 google-services.json in android/app/ and the Gradle plugin — Android platform setup. Firebase Messaging itself arrives through the package's Gradle module; add nothing to dependencies.

2 A monochrome status-bar icon at android/app/src/main/res/drawable/ic_notification.png (white on transparent), passed as androidSmallIcon. Android draws anything else as a grey square.

3 Android 13+: requestPermission() asks for POST_NOTIFICATIONS; the module's manifest declares it.

Autolinking picks the module up on the next build. Already have a FirebaseMessagingService? Forward onNewToken and onMessageReceived exactly as the Kotlin SDK documents — it is the same code.

iOS​

1 cd ios && pod install.

2 Xcode → app target → Signing & Capabilities → add Push Notifications and Background Modes → Remote notifications.

3 Forward four callbacks from AppDelegate. Swift:

import OpenNotification
import UserNotifications

// in application(_:didFinishLaunchingWithOptions:)
UNUserNotificationCenter.current().delegate = self
OpenNotification.setLaunchNotification(launchOptions?[.remoteNotification] as? [AnyHashable: Any])

func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
OpenNotification.didRegister(deviceToken: deviceToken)
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
OpenNotification.didFailToRegister(error: error)
}

extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
OpenNotification.didReceive(response: response)
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
OpenNotification.willPresent(notification: notification)
completionHandler(OpenNotification.presentationOptions(for: notification))
}
}

Objective-C AppDelegate.mm: #import "YourApp-Swift.h" and call the same four OpenNotification class methods.

Without these, permission is granted, no token ever arrives, and requestPermission() resolves with no_token.

4 Notification Service Extension — required for delivered, images and buttons on iOS:

  1. File → New → Target… → Notification Service Extension, name it NotificationService, deployment target = app's.
  2. Replace its NotificationService.swift with node_modules/@opennotification/react-native/ios/NotificationServiceExtension/NotificationService.swift.
  3. In the extension's Info.plist add String OpenNotificationApiUrl = your API base URL.
  4. Give it its own App ID / profile (com.acme.app.NotificationService).

5 Upload the .p8 — iOS platform setup.

What reports what​

EventiOSAndroid
deliveredNotification Service ExtensionFirebaseMessagingService (native)
openeddidReceive response → native moduleNotificationReceiver (native)
clicked (button)didReceive with an action identifierNotificationReceiver with the button id
dismissednot available on iOSNotificationReceiver (native)

On Android every ping is sent natively — FCM may wake the process with no JavaScript in it — and the JavaScript client only relays events to your listeners. On iOS the client reports opens itself.

Notes​

  • Messages are normalised: APNs on block and FCM flat data both arrive as one OpenNotificationMessage.
  • Only types are imported from @opennotification/core — nothing from the server ends up in your bundle.
  • The subscription id lives in UserDefaults / SharedPreferences. Pass your own storage to createClient if the app would rather own persistence; without any native module (tests) it stays in memory and the device re-registers next launch, which upserts the same row by token.