@flash-analytics/react-native
v2.1.9
Published
```bash npm install @flash-analytics/react-native cd ios && pod install ```
Downloads
801
Readme
Flash Analytics React Native SDK
Install
npm install @flash-analytics/react-native
cd ios && pod installQuick Start
import { FlashAnalytics } from '@flash-analytics/react-native';
const analytics = new FlashAnalytics({
appId: 'your-app-id',
endpoint: 'https://api.flashanalytics.app',
captureScreenViews: true,
captureAppLifecycle: true,
captureDeepLinks: true,
capturePushLifecycle: true,
});When captureAppLifecycle is enabled, app_opened is emitted only after the
React Native app is actually foregrounded. Background/headless notification
handlers should not trigger app_opened.
Auto-Tracking Matrix
| Capability | Status | Notes |
| --- | --- | --- |
| App lifecycle | Auto | JS AppState handles this by default; Android can also use the native lifecycle module |
| Deep links | Auto | JS Linking integration tracks cold-start and foreground URL opens |
| Screen views | SDK-assisted | Requires navigation wiring via setNavigationRef(...) or trackScreenChange(...) |
| Push delivered/open/dismiss/action | SDK-assisted | Requires native iOS/Android integration; JS alone cannot observe every OS push callback |
| Push expired | SDK-assisted | iOS uses service extension expiry; Android uses payload expiresAt or fallback defaultNotificationTtlMs |
| JS errors / unhandled rejections | Auto | Enable via captureErrors: true — uses SDK's own credentials |
| Native crashes (iOS/Android) | Auto | Enable via captureNativeCrashes: true; crash is persisted to disk and flushed as native_crash on next launch |
| Experiment auto-assignment | Auto | Enable via captureVariants: true — fetches assigned variants on session start and identify() |
Initialization and Usage
Initialize the SDK by providing your App ID. You can also pass optional parameters to automatically capture deep links, app lifecycle events, screen views, and application errors.
import { FlashAnalytics } from '@flash-analytics/react-native';
// 1. Initialize the SDK
const analytics = new FlashAnalytics({
appId: 'your-app-id',
// Optional Auto-Tracking Features
captureAppLifecycle: true,
captureScreenViews: true,
captureDeepLinks: true,
// Auto-capture JS errors and unhandled promise rejections (uses SDK's own credentials)
captureErrors: true,
// Enable native crash tracking (ObjC exceptions + signals on iOS, JVM uncaught on Android)
// Crashes are written to disk and flushed as native_crash events on the next launch
captureNativeCrashes: true,
// Auto-assign experiments on session start and identify()
captureVariants: true,
// captureVariants: { modes: ['session'], onAssignmentsChanged: (a) => {} },
});
// 2. Standard Event Tracking
await analytics.track('page_view');
// 3. Manual Error Tracking
// Use this for errors you catch gracefully so they don't trigger global crashes.
try {
// Simulate a failing network request
throw new Error('Failed to fetch user data');
} catch (error) {
// Manually send the caught error to Flash Analytics
analytics.trackError(error, 'network_failure');
}
// 4. Session Access
// Use getSession() when you need both the session id and its estimated expiry.
const session = analytics.getSession();
console.log(session?.id);
console.log(session?.estimatedExpiresAt);
console.log(session?.estimatedTtlMs);Use getSession() when you need both the session id and its estimated expiry.
Notification Lifecycle Manual
The React Native SDK supports notification lifecycle tracking through the same
track() pipeline, but iOS and Android native setup is still required.
These setup steps are not Firebase-only. They also apply to AppsFlyer and other notification providers as long as the final delivery path still goes through the standard iOS / Android notification hooks.
Events supported by the SDK:
notification_deliverednotification_openednotification_dismissednotification_action_clickednotification_expired(iOS:serviceExtensionTimeWillExpire(); Android: payloadexpiresAtor optional fallbackdefaultNotificationTtlMs)
Important constraint:
- React Native JavaScript cannot capture all push lifecycle events by itself.
- iOS delivery tracking requires a native
UNNotificationServiceExtension. - Android dismiss and action tracking requires native
BroadcastReceiver/PendingIntent/WorkManagerintegration.
Step 1: Enable the feature in React Native
import { FlashAnalytics } from '@flash-analytics/react-native';
const analytics = new FlashAnalytics({
appId: 'your-app-id',
endpoint: 'https://api.flashanalytics.app',
capturePushLifecycle: true,
pushTracking: {
android: {
defaultChannelId: 'flash-default',
defaultNotificationTtlMs: 5 * 60 * 1000,
},
},
});On Android, payload expiresAt still takes precedence. defaultNotificationTtlMs
is only used when the notification payload does not include expiresAt.
Optional manual calls from JS:
await analytics.trackNotificationOpened({
notificationId: 'notif_123',
messageId: 'fcm_123',
provider: 'firebase', // or 'appsflyer', etc.
});If your provider uses different payload keys, map them into the standard Flash properties before tracking:
notificationIdmessageIdcampaignIdprovideractionIdactionLabel
If the native module is installed, you can also attach the native event stream:
const detachNativeTracking = analytics.attachNativeNotificationTracking();Or configure the native module manually at startup:
enableFlashPushTracking({
appId: 'your-app-id',
endpoint: 'https://api.flashanalytics.app',
android: {
defaultChannelId: 'flash-default',
defaultNotificationTtlMs: 5 * 60 * 1000,
},
});Step 2: iOS manual setup
The app developer must do this manually in Xcode:
- Open
ios/<App>.xcworkspace - Add a new target:
File->New->Target->Notification Service Extension - Add your extension file, for example
NotificationService.swift - Include Flash Analytics native iOS support in that extension target
- Send push payloads with
mutable-content: 1
Example payload requirement:
{
"aps": {
"mutable-content": 1
}
}Example extension shape:
import UserNotifications
import FlashAnalytics
final class NotificationService: UNNotificationServiceExtension {
// lazy var — one FlashAnalytics instance per notification lifecycle.
private lazy var analytics = FlashAnalytics(
options: FlashAnalyticsOptions(
appId: "your-app-id",
endpoint: "https://api.flashanalytics.app"
)
)
private var bestAttemptRequest: UNNotificationRequest?
override func didReceive(
_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
) {
bestAttemptRequest = request
if let payload = FlashNotificationPayload.from(
userInfo: request.content.userInfo,
fallbackNotificationId: request.identifier
) {
analytics.trackNotificationDelivered(
payload: payload,
source: "ios_service_extension"
)
}
contentHandler(request.content)
}
override func serviceExtensionTimeWillExpire() {
guard
let request = bestAttemptRequest,
let payload = FlashNotificationPayload.from(
userInfo: request.content.userInfo,
fallbackNotificationId: request.identifier
)
else { return }
analytics.trackNotificationExpired(
payload: payload,
source: "ios_service_extension"
)
}
}App-side iOS notification response handling should also track:
notification_openednotification_dismissednotification_action_clicked
Step 3: Android manual setup
The app developer should:
- Register native notification receivers in
AndroidManifest.xml - Use notification
deleteIntentfor dismissals - Use action
PendingIntents for button actions - Forward the resulting
Intentinto the Flash Android SDK - Use
WorkManagerif the event may outlive the process
Example Android native call:
analytics.trackNotificationEvent(
event = FlashNotificationEvent.DISMISSED,
intent = intent,
source = "android_broadcast_receiver",
appState = "background"
)What is manual?
Yes, some setup is manual:
- iOS: required manual Xcode target setup
- Android: usually manifest and notification intent wiring
The SDK provides the event API and tracking helpers, but the OS-level hooks must be connected by the app.
