API reference
Every export of the React Native packages — startup, hooks, logs and errors, sessions, users, network recording, bundle ids, types, the tracer provider, navigation, Redux and OTLP — with signatures, fallbacks and where Android and iOS behave differently.
Everything below is imported from @sophonz/react-native unless another package is named. Every call that reaches the native SDK returns a promise that never rejects: if the native side fails, the promise resolves to a fallback — false, an empty string or "INVALID" — so instrumentation cannot break the app. To see why a call fell back, turn on SDK error logging.
Startup
initialize
initialize(args?: {
sdkConfig?: SDKConfig;
patch?: string;
logLevel?: SophonzLoggerLevel;
}): Promise<boolean>Starts the native SDK if it is not running, then installs the global error handler. Resolves true when the SDK is running and the handler is installed.
It resolves false when the native module is not linked, when the start fails (on iOS: no collector and key, no plist, no exporters), when an exporters block is invalid, or when ErrorUtils is not available. Call it once. Options are described in Configuration.
NOTE — What initialize does after the start
It records the React Native version and the package version, sets patch when given, installs a global handler through ErrorUtils that logs unhandled JS exceptions before passing them to the previous handler, and, with trackUnhandledRejections, logs unhandled promise rejections. In a release build on iOS it also computes an identifier for main.jsbundle. All of this happens even when the SDK was started natively; only the start options are skipped.
Hooks
| API | Returns | Description |
|---|---|---|
useSophonz(sdkConfig, patch?, logLevel?) | {isPending, isStarted} | Calls initialize in an effect. Re-runs when an argument changes identity while not started, so keep sdkConfig stable |
useSophonzIsStarted() | boolean | null | Whether the native SDK is running. null until the first answer |
useOrientationListener(enabled = true) | void | Adds a breadcrumb for the starting orientation and each change between portrait and landscape |
SDK error logging
| API | Description |
|---|---|
configureSDKErrorLogging(config: Partial<SDKErrorLoggingConfig>) | Merges into the current config. {enabled, allowLogToConsole, customHandler(methodName, error)}, all off by default |
getSDKErrorLoggingConfig() | A copy of the current config |
Logs and errors
| API | Returns | Description |
|---|---|---|
logInfo(message) | Promise<boolean> | INFO log, never with a stack trace |
logWarning(message, includeStacktrace = true) | Promise<boolean> | WARN log |
logError(message, includeStacktrace = true) | Promise<boolean> | ERROR log |
logMessage(message, severity = "error", properties = {}, includeStacktrace = true) | Promise<boolean> | Log with properties. severity is "info", "warning" or "error" |
logHandledError(error, properties = {}) | Promise<boolean> | ERROR log for a caught Error, with its JS stack and spz.exception_handling: handled. Resolves false for anything not instanceof Error |
logIfComponentError(error) | Promise<boolean> | ERROR log of an error's React componentStack. Resolves false when there is none |
addBreadcrumb(message) | Promise<boolean> | A breadcrumb event on the current session. Cheaper than a log |
import {logHandledError, logMessage} from "@sophonz/react-native";
try {
await checkout(cart);
} catch (e) {
logHandledError(e as Error, {cart_size: String(cart.length)});
}
logMessage("payment retried", "warning", {provider: "card"});- Properties must be strings. On iOS a non-string value makes the whole call resolve
falseand nothing is logged. Android converts other values. - The stack trace captured at the call site travels as the
spz.stacktrace.rnattribute. WithincludeStacktraceon and no JS stack available, iOS attaches the native stack instead. handleGlobalErrorandhandleErrorare also exported. They are the piecesinitializeinstalls and are not meant to be called directly.
Sessions
| API | Returns | Description |
|---|---|---|
getCurrentSessionId() | Promise<string> | The current session id: 32 lowercase hex characters, the same string that goes on the wire as session.id. "" on failure |
endSession() | Promise<boolean> | Ends the current session and starts a new one |
addSessionProperty(key, value, permanent) | Promise<boolean> | A property on the session. permanent: true keeps it on later sessions until removed |
removeSessionProperty(key) | Promise<boolean> | Removes it, whichever lifespan it was added with |
getLastRunEndState() | Promise<SessionStatus> | "CRASH" or "CLEAN_EXIT" for the previous launch; "INVALID" when the SDK is not started |
getDeviceId() | Promise<string> | The SDK's device identifier. "" on failure |
getLastRunEndState does not change until the next cold launch, so it can be read at any point to show a "the app closed unexpectedly" message.
Inside an AppState listener the session may already be ending; getCurrentSessionId can return the id of the session that is closing.
Users
| API | Returns | Description |
|---|---|---|
setUserIdentifier(id), clearUserIdentifier() | Promise<boolean> | User identifier, kept for later sessions |
addUserPersona(persona), clearUserPersona(persona), clearAllUserPersonas() | Promise<boolean> | Classification tags. On iOS a persona lasts for the current session |
setUsername(name), clearUsername() | Promise<boolean> | Username — Android only; iOS resolves false |
setUserEmail(email), clearUserEmail() | Promise<boolean> | Email address — Android only; iOS resolves false |
Call clearUserIdentifier on logout.
CAUTION — Choosing an identifier
Values are stored as given. An internal identifier is safer than an email address or a real name; check that what you send fits your privacy policy.
Network
Requests made through fetch and XMLHttpRequest are captured natively. Record manually only what the SDKs cannot see; see Networking.
| API | Returns | Description |
|---|---|---|
recordNetworkRequest(url, httpMethod, startInMillis, endInMillis, bytesSent?, bytesReceived?, statusCode?) | Promise<boolean> | A completed request. 0 or a missing number is recorded as unknown |
logNetworkClientError(url, httpMethod, startInMillis, endInMillis, errorType, errorMessage) | Promise<boolean> | A request that got no HTTP response |
httpMethod is a MethodType: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, CONNECT, TRACE, PURGE, LINK or UNLINK, upper or lower case. Times are epoch milliseconds.
The span carries spz.w3c_traceparent on iOS unless ios.disableNetworkSpanForwarding is set, and on Android only when networking.enable_network_span_forwarding is on.
Bundle identification
| API | Returns | Description |
|---|---|---|
setJavaScriptPatch(patch) | Promise<boolean> | Records a patch identifier, for over-the-air updates. initialize({patch}) calls it |
setJavaScriptBundlePath(path) | Promise<boolean> | Identifies the running JS bundle by its contents. iOS hashes the file (MD5) and records it as react_native_bundle_id; iOS release builds call it automatically for main.jsbundle |
Call setJavaScriptBundlePath yourself after an over-the-air update loads a bundle from another path.
Types
| Type | Definition |
|---|---|
SDKConfig | {ios?: IOSConfig; exporters?: OTLPExporterConfig; trackUnhandledRejections?: boolean; logLevel?: SophonzLoggerLevel}. logLevel here is not read |
IOSConfig | {collectorUrl?, appKey?, appName?, project?, deploymentEnvironment?: string; disableCrashReporter?, disableAutomaticViewCapture?, disableNetworkSpanForwarding?: boolean; disabledUrlPatterns?: string[]} |
AndroidConfig | {} — Android is configured at build time |
OTLPExporterConfig | {logExporter?: ExporterConfig; traceExporter?: ExporterConfig} |
ExporterConfig | {endpoint: string; headers?: {key: string; token: string}[]; timeout?: number} |
LogProperties | {[key: string]: string} |
LogSeverity | "info" | "warning" | "error" |
SessionStatus | "INVALID" | "CRASH" | "CLEAN_EXIT" |
SophonzLoggerLevel | "info" | "warn" | "error" |
MethodType | The HTTP methods listed under Network |
ComponentError | Error & React.ErrorInfo |
SDKErrorLoggingConfig | {enabled: boolean; allowLogToConsole: boolean; customHandler?: (methodName: string, error: Error) => void} |
Tracing — @sophonz/react-native-tracer-provider
Guide: OpenTelemetry and OTLP.
| API | Description |
|---|---|
useSophonzNativeTracerProvider(config?, enabled = true) | Creates the provider once enabled is true and the SDK is running. Returns {tracerProvider, tracer, isLoading, isError, error} |
new SophonzNativeTracerProvider(config?) | The provider without the hook. Does not check that the SDK is running |
provider.getTracer(name, version?, {schemaUrl?}?) | A SophonzNativeTracer. schemaUrl is ignored on iOS |
tracer.startSpan(name, options?, context?), tracer.startActiveSpan(...) | Standard OpenTelemetry signatures |
(span as SophonzNativeSpan).spanContextAsync() | Promise<SpanContext> that resolves once the native side has assigned ids |
startView(tracer, name) | A span shaped as a screen view |
recordCompletedSpan(tracer, name, options?) | Starts and ends a span in one call, with events, status and parent. Options type: CompletedSpanOptions |
asParent(span) | A context in which span is the parent |
endAsFailed(span) | Sets ERROR status and ends |
| Config type | Fields |
|---|---|
SophonzNativeTracerProviderConfig | spanContextSyncBehaviour?: "return_empty" | "throw", setGlobalContextManager?: boolean |
SophonzNativeTracerProviderReturn | {isLoading, isError: boolean; error: string; tracerProvider: TracerProvider | null; tracer: Tracer | null} |
Navigation — @sophonz/react-native-navigation
Guide: Navigation.
| API | Description |
|---|---|
SophonzNavigationTracker | For expo-router and React Navigation. Props: ref, tracerProvider?, screenAttributes?, tracerOptions?, debug? (default true), children |
SophonzNativeNavigationTracker | For react-native-navigation, with a ref to Navigation.events(). Same props |
Redux — @sophonz/react-native-redux
Guide: Redux.
| API | Description |
|---|---|
useSophonzMiddleware(tracerProvider?) | Returns {middleware} once the provider is set |
createSophonzMiddleware(tracerProvider) | The middleware without the hook |
Each dispatched action becomes a span named action of type sys.rn_action carrying the action type, the outcome and the payload size.
OTLP — @sophonz/react-native-otlp
Configured through sdkConfig.exporters; see Additional OTLP exporters. The package exports initialize(exporterConfig), which the core package calls during its start, and re-exports the config types. You do not call it yourself.
Platform differences
| Behaviour | Android | iOS |
|---|---|---|
setUsername, setUserEmail and their clear* | Recorded | Resolve false; the Apple SDK has no such fields |
| Calls made before the SDK has started | Handed to the SDK | Resolve their fallback |
logMessage properties that are not strings | Converted | The call resolves false |
| Personas | As the Android SDK scopes them | Last for the current session |
| React Native version, JS patch, bundle identifier | Resource attributes | Process-lifespan properties |
| Unhandled JS exception | A typed React Native crash log | An ERROR log with exception.type, exception.message and the JS stack |
spz.w3c_traceparent on manually recorded requests | With enable_network_span_forwarding | Unless disableNetworkSpanForwarding |
| Span kind from the tracer provider | Kept | Ignored; every span is internal |
span.updateName | Applied | Ignored |
| Tracer name, version, schema URL | Recorded | Not recorded |
| Array attribute values | Kept | Recorded as a string |
| Span links | Passed to the SDK | Passed to the SDK |
The iOS rows follow from the public API of the Apple SDK, which the React Native module is limited to. Where a difference matters for a dashboard, filter by client.platform.