React Native SDK
Expo plugin, native wiring, and JS API for @comraid/react-native.
Thin TurboModule bridge over the ComRaid Android and Apple SDKs
(@comraid/react-native): initialize, register, Login, RNFirebase-shaped
receive events, presentNotification, and local schedules.
Canonical method reference lives on this page. The package README stays at parity — see the comraid-react-native README.
Install
Install @comraid/react-native. Requires React Native New Architecture with
Codegen, React Native 0.79+, iOS 15+, and Android API 24+. Host apps supply
Firebase Messaging (Android) and APNs (iOS). Expo apps need a development or
production build — Expo Go cannot load this native module.
npm install @comraid/react-nativeFor Expo, add the config plugin under expo.plugins. App ID is still passed at
runtime via initialize. See Push providers and
the Android / iOS SDK pages for provider wiring.
{
"expo": {
"android": {
"googleServicesFile": "./google-services.json"
},
"plugins": [
[
"@comraid/react-native",
{
"android": {
"defaultChannelId": "general",
"defaultChannelName": "General",
"smallIconResourceName": "ic_notification",
"defaultNotificationColor": "#111827"
},
"ios": {
"storageSuiteName": "group.com.example.app.comraid",
"apnsEnvironment": "sandbox",
"notificationServiceExtension": true
}
}
]
]
}
}The plugin:
- Applies Google Services and host
firebase-messagingfromandroid.googleServicesFile(Expo config or plugin option) - Writes Android meta-data for default channel / small icon / color
(
com.comraid.*) - Declares
POST_NOTIFICATIONS - Registers
com.comraid.android.internal.ComraidMessagingServicefor FCM (disable withandroid.includeMessagingService: falseif the host subclasses it) - Wires iOS APNs token + notification delegate without hand-edited AppDelegate
- Adds iOS
UIBackgroundModesremote-notification - Optionally sets
aps-environmentwhenios.apnsEnvironmentissandboxorproduction - With
ios.storageSuiteName, adds the App Group entitlement on the main app - With
ios.notificationServiceExtension: true, adds a Notification Service Extension for push images, cold-device action buttons, and delivered ACK (passesstorageSuiteNameintoRemoteNotificationDisplay.enrich, App Group on the extension), registers it with EAS Build, and links theComRaidpod — see Images and action buttons (iOS)
Getting started
Use a publishable cr_app_… id from Push → Push settings → Platforms.
Vocabulary: Subscription, external_user_id, Identity verification JWT
(login(externalUserId, jwt)), Contact Attributes, Subscription
Properties. Server-side sends use Message / Notification with secret
API keys (cr_sk_…) or the Dashboard — Single send, Broadcast, and
Multi-send (/campaigns) — not this mobile package. Delivery outcomes are
sent, delivered, opened, skipped, and failed; Message
statuses include scheduled, preparing, processing, completed,
failed, and cancelled.
Logout means Inactive (Endpoint state): the server clears the Subscription
credential and the native SDK clears persisted identity (Android encrypted
prefs / iOS Keychain) then registers a fresh Subscription. Native SDKs persist
Subscription id, credential, and External user ID across launches and send the
credential on register. On iOS, APNs token updates via the bridge call
setAPNsDeviceToken, which refreshes /token when a credential exists.
Channel opt-out is Contact × Channel — not a OneSignal-style subscription-only
mute. There is no JS HTTP client for mobile routes (ADR 0004); identity and HTTP
live in the native SDKs.
import { ComRaid } from '@comraid/react-native';
await ComRaid.initialize({
appId: 'cr_app_your_id',
// apiBaseURL: 'http://localhost:8080',
android: {
smallIconResourceName: 'ic_notification',
},
ios: {
apnsEnvironment: 'sandbox', // or 'production'
},
});
const caps = await ComRaid.getCapabilities();
const granted = await ComRaid.requestNotificationPermission();
// Android registers on grant. On iOS, forward the APNs token in native AppDelegate
// via ComraidBridge.setAPNsDeviceToken (Expo config plugin does this after prebuild), then:
await ComRaid.register();
await ComRaid.login('user_123');
await ComRaid.login('user_123', jwtFromYourBackend); // Identity verification JWT
await ComRaid.setDeviceProperties({ appVersion: '1.2.0', model: 'Pixel 8' });
await ComRaid.setAttributes({ plan: 'premium' });
await ComRaid.logout(); // Subscription becomes InactiveMigrating from @react-native-firebase/messaging or Notifee? See
Migrate from RNFirebase (migrate-only —
do not run two messaging services). Data-only Content:
Notifications. On Android, the native messaging service
presents alert Notifications and acks delivered in the background. On iOS,
delivered (and images / cold-device action buttons) need a Notification Service
Extension — see
Images and action buttons (iOS).
SubscribeBanner
After initialize, use the first-party SubscribeBanner React component for OS
notification permission → register a Subscription → optional Login with
an External user ID (and Identity verification jwt when your Project
requires it). Omit identity props to leave an Anonymous contact after
register. The banner never drives Channel Opted out — it does not call Channel
opt-in / opt-out APIs.
Secondary dismiss only notifies your app via onDismiss; the SDK does not
persist snooze / re-prompt intervals. Denied permission shows recovery copy and
an optional onPermissionDenied host callback (opening OS Settings is your job
if you want it).
import { useState } from 'react';
import { ComRaid, SubscribeBanner } from '@comraid/react-native';
await ComRaid.initialize({
appId: 'cr_app_your_id',
ios: { apnsEnvironment: 'sandbox' },
});
function Prompt() {
const [visible, setVisible] = useState(true);
if (!visible) return null;
return (
<SubscribeBanner
externalUserId="user_123" // omit for Anonymous contact after register
// jwt={jwtFromYourBackend}
onDismiss={() => setVisible(false)}
onSuccess={() => setVisible(false)}
onError={(err) => console.warn(err)}
/>
);
}Receive and present
JS APIs match RNFirebase messaging names. Data-only Notifications never
auto-draw; call presentNotification to promote to the tray (action taps
auto-ACK opened). Register the background handler from the app entry file before
other setup.
import { ComRaid } from '@comraid/react-native';
// index.js / entry — before AppRegistry
ComRaid.setBackgroundMessageHandler(async (message) => {
// data-only or background receive
});
ComRaid.onMessage((message) => {
// foreground; sender data keys in message.data
});
ComRaid.onNotificationOpenedApp((message) => {
// background → tap (message.actionId when an action was pressed)
});
const initial = await ComRaid.getInitialNotification();
const token = await ComRaid.getToken(); // Provider FCM/APNs token
ComRaid.onTokenRefresh((token) => {});
await ComRaid.presentNotification(message); // optional local tray + actionsReceive event fields
RemoteMessage (from onMessage, setBackgroundMessageHandler,
onNotificationOpenedApp, and getInitialNotification) matches the native
receive shape. Optional presentation fields are absent (undefined) when not
set — never empty strings. Wrong-typed values are dropped by the parser.
priority is always 'high' | 'normal' on received events (default 'high').
| Field | Type | Source | Platform notes |
|---|---|---|---|
imageUrl | string? | cr_image_url | Shown by presentNotification on both platforms; iOS OS-drawn alerts also need a Notification Service Extension. |
subtitle | string? | cr_subtitle, else iOS aps.alert.subtitle | Drawn on iOS only; Android exposes it but never draws it. |
sound | string? | cr_sound, else iOS aps.sound | Raw value as sent. iOS applies it on present; Android 8+ uses the Category channel (ADR 0012), Android 7 and older use sound. |
badge | number? (≥ 0) | cr_badge, else iOS aps.badge | Applied on present on both platforms. |
threadId | string? | cr_thread_id, else iOS aps.thread-id | Android notification tag / iOS thread grouping. |
androidChannelId | string? | cr_android_channel_id | Android channel for present; carried on iOS for parity, not drawn. |
priority | 'high' | 'normal' | cr_priority (else default / APNs hint) | Always present on received events. |
message.data stays sender keys only.
presentNotification
presentNotification(message) draws the title, body, actions and deep link,
plus every presentation field on the message. Platform rules match the native
SDKs:
| Field | Android | iOS |
|---|---|---|
imageUrl | Expanded picture / large icon | Attached (NSE still required for OS-drawn alerts) |
subtitle | Not drawn | Drawn |
sound | Android 7 and older only; 8+ via Category channel (ADR 0012) | Applied |
badge | Notification count | App icon badge |
threadId | Notification tag | Thread identifier |
androidChannelId | Posts on that channel when known | Not drawn |
priority | Android 7 and older only; 8+ via channel importance | Carried, not drawn into content |
Hand-built messages work the same way as received ones. Requires a non-blank
title. iOS images (and cold-device action buttons) for OS-drawn alerts:
Images and action buttons (iOS) — Expo
ios.notificationServiceExtension: true, or a bare/native extension that calls
RemoteNotificationDisplay.enrich.
Method reference
Public surface is ComRaid from @comraid/react-native (TurboModule
NativeComraid). Grouped by lifecycle. Examples are clustered per group, not
per method.
Configure
initialize(options: ConfigureOptions): Promise<void> — stores settings on the
native SDKs. Does not register a Subscription — call
requestNotificationPermission / register after permission is granted.
| Parameter | Type | Required | Description |
|---|---|---|---|
options.appId | string | yes | Publishable App ID (cr_app_…) |
options.apiBaseURL | string | no | API base; native default https://api.comraid.io |
options.displayForegroundNotifications | boolean | no | Default true: SDK shows non–data-only alerts in the foreground. Set false to handle alerts only via onMessage |
options.android.defaultChannelId | string | no | Android notification channel id |
options.android.defaultChannelName | string | no | Android notification channel name |
options.android.smallIconResourceName | string | no | Drawable resource name for the small icon |
options.ios.apnsEnvironment | 'sandbox' | 'production' | yes on iOS | APNs environment |
options.ios.storageSuiteName | string | no | App Group id shared with the Notification Service Extension (delivered ACK + durable queue) |
Returns: Promise<void>
configure(options: ConfigureOptions): Promise<void> — deprecated alias of
initialize. Prefer initialize.
await ComRaid.initialize({
appId: 'cr_app_your_id',
apiBaseURL: 'http://localhost:8080',
android: { smallIconResourceName: 'ic_notification' },
ios: { apnsEnvironment: 'sandbox' },
});Capabilities and permission
getCapabilities(): Promise<Capabilities> — reads platform notification /
exact-alarm capability from the native SDK.
| Parameter | Type | Required | Description |
|---|---|---|---|
| — | — | — | No parameters |
Returns: Promise<Capabilities> — platform, notificationsEnabled,
authorizationStatus (authorized, denied, or on Android notDetermined before the first prompt), exactAlarmsAvailable
requestNotificationPermission(): Promise<boolean> — requests OS notification
permission only; it does not register a Subscription. Call register() after a
grant. On iOS, make sure the APNs token is forwarded natively first (the Expo
config plugin does this after prebuild).
| Parameter | Type | Required | Description |
|---|---|---|---|
| — | — | — | No parameters |
Returns: Promise<boolean> — whether permission was granted
register(): Promise<void> — registers (or refreshes) the push Subscription
with the current device token. Native SDKs send a persisted
subscription_credential when present so refresh keeps the same Subscription.
| Parameter | Type | Required | Description |
|---|---|---|---|
| — | — | — | No parameters |
Returns: Promise<void>
const caps = await ComRaid.getCapabilities();
if (!caps.notificationsEnabled) {
await ComRaid.requestNotificationPermission();
}
await ComRaid.register();Identity
login(externalUserId: string, jwt?: string): Promise<void> — associates the
Subscription with a Contact (external_user_id). Optional Identity verification
JWT.
| Parameter | Type | Required | Description |
|---|---|---|---|
externalUserId | string | yes | Contact external_user_id (non-empty) |
jwt | string | no | Identity verification JWT from your backend |
Returns: Promise<void>
logout(): Promise<void> — makes the Subscription Inactive, clears its
server credential, and has the native SDK register a fresh Subscription on a
new Anonymous contact. Mobile routes refuse the old row with 401 unauthorized
or 409 subscription_inactive.
| Parameter | Type | Required | Description |
|---|---|---|---|
| — | — | — | No parameters |
Returns: Promise<void>
await ComRaid.login('user_123', jwtFromYourBackend);
await ComRaid.logout();Properties and Attributes
Native Android / iOS SDKs auto-collect app/SDK version, OS, model, locale,
language, timezone and country on register and eligible foregrounds, and POST
/session with a ~30 minute background debounce. React Native inherits that
behavior through the native modules.
setDeviceProperties(properties: DeviceProperties): Promise<void> — optional
overrides for auto-collected Properties on the next native register / token /
session call.
| Parameter | Type | Required | Description |
|---|---|---|---|
properties.appVersion | string | no | App version string |
properties.model | string | no | Device model |
properties.osVersion | string | no | OS version string |
properties.extras | Record<string, unknown> | no | Additional plain-object fields |
Returns: Promise<void>
setAttributes(attributes: ContactAttributes): Promise<void> — upserts Contact
Attributes for the logged-in external_user_id. Requires Login. Values are
string | number | boolean | null. See
Contact attributes.
| Parameter | Type | Required | Description |
|---|---|---|---|
attributes | ContactAttributes | yes | Plain object of attribute keys (string | number | boolean | null). A null value removes that Attribute. |
Returns: Promise<void>
await ComRaid.setDeviceProperties({
appVersion: '1.2.0',
model: 'Pixel 8',
osVersion: '14',
extras: { carrier: 'demo' },
});
await ComRaid.setAttributes({ plan: 'premium', seats: 3 });Delivery ACKs
Remote display and durable ACK enqueue usually run inside the native FCM / APNs
path. JS can also forward explicit ACKs. Auth remains the per-delivery
cr_attribution_token. See Acknowledgements.
acknowledgeDelivered(deliveryId: string, attributionToken: string): Promise<boolean>
— enqueue + flush a delivered ACK. Returns false when ids are blank.
acknowledgeOpened(deliveryId: string, attributionToken: string, actionId?: string): Promise<boolean>
— enqueue + flush an opened ACK (optional action button id).
flushAcks(): Promise<void> — flushes any durable ACK backlog.
await ComRaid.acknowledgeDelivered(deliveryId, attributionToken);
await ComRaid.acknowledgeOpened(deliveryId, attributionToken, 'accept');
await ComRaid.flushAcks();Local schedule and timers
Local notifications only — not server Message / Campaign sends. Prefer ComRaid schedule APIs over Expo local notification helpers when using this package.
schedule(options: ScheduleOptions): Promise<ScheduleResult> — schedules a
local notification at a future trigger time.
| Parameter | Type | Required | Description |
|---|---|---|---|
options.notification | NotificationContent | yes | id, title, body; optional string-only data |
options.triggerAt | Date | number | yes | Future Date or Unix time in milliseconds |
options.precision | 'inexact' | 'exact' | no | Default 'inexact' |
options.fallbackPolicy | 'fail' | 'useInexact' | no | Default 'fail' when exact is unavailable |
Returns: Promise<ScheduleResult> — id, requestedPrecision,
appliedPrecision, triggerAt, optional fallbackReason
startTimer(options: TimerOptions): Promise<ScheduleResult> — starts a
countdown timer that fires a Local notification after durationMs (Android and
iOS).
| Parameter | Type | Required | Description |
|---|---|---|---|
options.notification | NotificationContent | yes | Same as schedule |
options.durationMs | number | yes | Positive duration in milliseconds |
options.precision | 'inexact' | 'exact' | no | Default 'inexact' |
options.fallbackPolicy | 'fail' | 'useInexact' | no | Default 'fail' |
Returns: Promise<ScheduleResult>
pauseTimer(id: string): Promise<Timer> — pauses a running timer and stores
remaining duration.
resumeTimer(id: string): Promise<Timer> — resumes a paused timer from
remaining duration.
cancelTimer(id: string): Promise<void> — cancels a timer and removes its
pending schedule.
timers(): Promise<Timer[]> — lists persisted timers (running / paused /
cancelled / completed).
cancel(id: string): Promise<void> — cancels a pending local schedule by
notification id.
pendingSchedules(): Promise<PendingSchedule[]> — lists pending local
schedules.
const scheduled = await ComRaid.schedule({
notification: {
id: 'reminder-1',
title: 'Reminder',
body: 'Time to check in.',
data: { screen: 'home' },
},
triggerAt: Date.now() + 60_000,
precision: 'inexact',
});
const timer = await ComRaid.startTimer({
notification: {
id: 'focus-1',
title: 'Focus complete',
body: 'Your timer has finished.',
},
durationMs: 25 * 60 * 1000,
});
await ComRaid.pauseTimer(timer.id);
await ComRaid.resumeTimer(timer.id);
const allTimers = await ComRaid.timers();
await ComRaid.cancelTimer(timer.id);
const pending = await ComRaid.pendingSchedules();
await ComRaid.cancel(scheduled.id);Exact alarms are platform opt-in (host permissions / policy). Defaults are inexact.
Errors
This package does not export a dedicated ComRaidError type. Failures surface
as:
| Kind | When |
|---|---|
Error | Native module not linked (e.g. Expo Go / missing rebuild) |
TypeError | Invalid JS arguments (appId, empty externalUserId, empty attributes, past triggerAt, non-positive durationMs, non-string notification.data values, etc.) |
| Native promise rejection | Platform / network / native SDK failures forwarded from Android / iOS |
Mobile HTTP error codes (forwarded from the native SDKs when the API returns them):
| Code | HTTP | When |
|---|---|---|
unauthorized | 401 | Missing or mismatched Subscription credential, or credential-less Endpoint. |
subscription_inactive | 409 | Login, opt-out/in, token, Attributes, or session on an Inactive Subscription. |
Not in this SDK
| Surface | Reason |
|---|---|
Message / Campaign send (/messages, /campaigns) | Mobile SDKs own Subscriptions and delivery — use the public API or @comraid/node |
Public JS session method | Native SDKs call /session automatically; no TurboModule method |
| iOS-only timer pause / resume / list APIs | Not bridged on the TurboModule (schedule / startTimer / cancel / pendingSchedules only) |
Deep links
ComRaid delivers deepLink on onNotificationOpenedApp and
getInitialNotification (from API content.push.deep_link / cr_deep_link).
The SDK never routes — your app decides whether and how to navigate. On Android
the native SDK opens the launch activity only; it does not fire ACTION_VIEW.
Route with React Navigation or Expo Router via React Native Linking:
import { Linking } from 'react-native';
import ComRaid from '@comraid/react-native';
function routeDeepLink(url: string | undefined) {
if (!url) return;
// React Navigation: linking config / navigationRef.navigate(...)
// Expo Router: router.push(url) or Linking.openURL for external https
void Linking.openURL(url);
}
ComRaid.onNotificationOpenedApp(message => {
routeDeepLink(message.deepLink);
});
void ComRaid.getInitialNotification().then(message => {
routeDeepLink(message?.deepLink);
});See Notification attribution and the Android / iOS SDK pages for payload details.
iOS SDK
Integrate ComRaid push on iOS with the Swift Package ComRaid — Subscription register, Login, Logout, Contact opt-in/out, remote display helpers, Notification Service Extension images, durable delivery ACKs, and local schedules/timers.
Contacts
Contacts are end recipients identified by your product’s external_user_id.