### Install Splunk OpenTelemetry for React Native
Source: https://github.com/hyperdxio/hyperdx-otel-react-native/blob/main/README.md
Install the library using npm or yarn. This is the first step to instrumenting your React Native application.
```bash
# npm
npm install @splunk/otel-react-native
# yarn
yarn add @splunk/otel-react-native
```
--------------------------------
### Start Navigation Tracking in React Native
Source: https://github.com/hyperdxio/hyperdx-otel-react-native/blob/main/README.md
Instrument navigation events for react-navigation versions 5 and 6. Ensure the navigation container is ready before starting tracking.
```javascript
import { startNavigationTracking } from '@splunk/otel-react-native';
export default function App() {
const navigationRef = useNavigationContainerRef();
return (
{
startNavigationTracking(navigationRef);
}}
>
...
);
}
```
--------------------------------
### Initialize Splunk RUM SDK
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Initialize the Splunk RUM SDK as early as possible in the application lifecycle. Requires `applicationName` and either `realm` or a custom `beaconEndpoint`. This setup configures the OpenTelemetry provider, instruments XHR, enables error tracking, and bootstraps the native SDK for span export and crash capture.
```typescript
import { SplunkRum } from '@splunk/otel-react-native';
// Minimal production setup targeting Splunk Observability Cloud
const rum = SplunkRum.init({
realm: 'us0', // Splunk Observability Cloud realm
rumAccessToken: 'your-rum-token', // RUM-specific access token
applicationName: 'MyMobileApp', // Identifies the app in Splunk
deploymentEnvironment: 'production',
debug: false,
});
// Advanced setup with a custom beacon, disk buffering, and global attributes
SplunkRum.init({
beaconEndpoint: 'https://ingest.example.com/v1/rum', // Overrides realm
rumAccessToken: 'your-rum-token',
applicationName: 'MyMobileApp',
allowInsecureBeacon: false, // Must be true to allow http://
appStartEnabled: true, // Track cold/warm app start spans (default: true)
enableDiskBuffering: true, // Buffer spans to disk before sending (default: true)
limitDiskUsageMegabytes: 25, // Cap disk buffer size
bufferTimeout: 5000, // BatchSpanProcessor flush delay in ms (default: 3000)
bufferSize: 30, // Max spans per export batch (default: 20)
globalAttributes: { // Attached to every span
'app.version': '2.3.1',
'build.env': 'release',
},
ignoreUrls: [
'https://analytics.internal.com',
/.*\.healthcheck\.io.*/, // Regex patterns also supported
],
});
```
--------------------------------
### Start Automatic Screen Navigation Spans
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Hooks into react-navigation to automatically emit OpenTelemetry spans for screen changes. Ensure your react-navigation version is compatible (v5 or v6).
```tsx
import React from 'react';
import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native';
import { startNavigationTracking, getCurrentView } from '@splunk/otel-react-native';
export default function App() {
const navigationRef = useNavigationContainerRef();
return (
{
// Begin tracking — fires a span for the initial screen immediately
startNavigationTracking(navigationRef);
console.log('Initial screen:', getCurrentView()); // e.g. "Home"
}}
>
{/* navigator content */}
);
}
```
--------------------------------
### Force New Session ID with SplunkRum._generatenewSessionId
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Immediately generate a new RUM session ID to start a fresh session, typically after user logout. This action emits a `sessionId.change` span.
```typescript
import { SplunkRum } from '@splunk/otel-react-native';
function onUserLogout() {
// Clear user-specific global attributes
SplunkRum.setGlobalAttributes({ 'user.id': '', 'session.authenticated': false });
// Rotate the session so post-logout activity is in a new session
SplunkRum._generatenewSessionId();
// Emits span: "sessionId.change"
// Attributes:
// splunk.rum.previous_session_id: ""
// New session ID is propagated to native layer automatically
}
```
--------------------------------
### SplunkRum._generatenewSessionId
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Forces the generation of a new RUM session ID immediately. This action creates a `sessionId.change` span that records the previous session ID. It is useful for starting fresh sessions after user logout or when custom session boundaries are required.
```APIDOC
## SplunkRum._generatenewSessionId — Force a New Session
### Description
Generates a new RUM session ID immediately, creating a `sessionId.change` span that records the previous session ID. Useful for starting fresh sessions after logout or when custom session boundaries are required.
### Usage
```ts
import { SplunkRum } from '@splunk/otel-react-native';
function onUserLogout() {
// Clear user-specific global attributes
SplunkRum.setGlobalAttributes({ 'user.id': '', 'session.authenticated': false });
// Rotate the session so post-logout activity is in a new session
SplunkRum._generatenewSessionId();
// Emits span: "sessionId.change"
// Attributes:
// splunk.rum.previous_session_id: ""
// New session ID is propagated to native layer automatically
}
```
```
--------------------------------
### SplunkRum.finishAppStart
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Manually ends the `AppStart` span. This should be called when the application's initial render and data loading are fully complete. It is automatically called when using `OtelWrapper`, but needs manual invocation when using `SplunkRum.init()` directly.
```APIDOC
## SplunkRum.finishAppStart — End the App Start Span
### Description
Manually ends the `AppStart` span. Call this when the application's initial render and data loading are fully complete. When using `OtelWrapper`, this is called automatically on component mount. Call it manually when using `SplunkRum.init()` directly.
### Usage
```ts
import { SplunkRum } from '@splunk/otel-react-native';
// Manual init flow (no OtelWrapper)
SplunkRum.init({
realm: 'us0',
rumAccessToken: 'your-rum-token',
applicationName: 'MyApp',
appStartEnabled: true,
});
async function bootstrap() {
await loadRemoteConfig();
await prefetchCriticalData();
// Signal that the app is fully ready — ends the AppStart span
SplunkRum.finishAppStart();
// AppStart span attributes:
// component: "appstart"
// start.type: "cold" | "warm"
}
bootstrap();
```
```
--------------------------------
### Initialize Splunk RUM SDK with OtelWrapper Component
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Use the `OtelWrapper` React component to declaratively initialize the RUM SDK and automatically call `SplunkRum.finishAppStart()` when the component mounts. This is preferred over manual `SplunkRum.init()` calls for static configurations. Ensure `startNavigationTracking` is called within `onReady` of `NavigationContainer` for navigation tracking.
```tsx
import React from 'react';
import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { OtelWrapper, startNavigationTracking } from '@splunk/otel-react-native';
import type { ReactNativeConfiguration } from '@splunk/otel-react-native';
const RumConfig: ReactNativeConfiguration = {
realm: 'us0',
rumAccessToken: 'your-rum-token',
applicationName: 'MyApp',
deploymentEnvironment: 'production',
globalAttributes: { 'app.version': '1.0.0' },
};
const Stack = createNativeStackNavigator();
export default function App() {
const navigationRef = useNavigationContainerRef();
return (
// OtelWrapper initializes SplunkRum and ends the AppStart span on mount
{
startNavigationTracking(navigationRef);
}}
>
);
}
```
--------------------------------
### SplunkRum.init
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Initializes the Splunk RUM SDK. This function should be called as early as possible in your application's lifecycle. It requires essential configuration like `applicationName` and either a `realm` or a custom `beaconEndpoint`. Optional parameters allow for advanced configuration such as disk buffering, custom attributes, and URL filtering.
```APIDOC
## SplunkRum.init — Initialize the RUM SDK
Initializes the Splunk RUM SDK as early as possible in the application lifecycle. Requires `applicationName` and either `realm` (for Splunk Observability Cloud) or a custom `beaconEndpoint`. Sets up the OpenTelemetry provider, instruments XHR, enables error tracking, and bootstraps the native SDK for span export and crash capture.
### Parameters
- **realm** (string) - Required if `beaconEndpoint` is not provided - The Splunk Observability Cloud realm.
- **beaconEndpoint** (string) - Required if `realm` is not provided - A custom endpoint for beacon data.
- **rumAccessToken** (string) - Required - The RUM-specific access token.
- **applicationName** (string) - Required - Identifies the application in Splunk.
- **deploymentEnvironment** (string) - Optional - The deployment environment (e.g., 'production', 'staging').
- **debug** (boolean) - Optional - Enables debug logging (default: false).
- **allowInsecureBeacon** (boolean) - Optional - Allows insecure HTTP beacons (default: false).
- **appStartEnabled** (boolean) - Optional - Tracks cold/warm app start spans (default: true).
- **enableDiskBuffering** (boolean) - Optional - Buffers spans to disk before sending (default: true).
- **limitDiskUsageMegabytes** (number) - Optional - Caps the disk buffer size in megabytes.
- **bufferTimeout** (number) - Optional - BatchSpanProcessor flush delay in milliseconds (default: 3000).
- **bufferSize** (number) - Optional - Maximum number of spans per export batch (default: 20).
- **globalAttributes** (object) - Optional - Key-value pairs attached to every span.
- **ignoreUrls** (array) - Optional - A list of URLs or regex patterns to ignore for tracing.
### Request Example
```ts
import { SplunkRum } from '@splunk/otel-react-native';
// Minimal production setup targeting Splunk Observability Cloud
const rum = SplunkRum.init({
realm: 'us0',
rumAccessToken: 'your-rum-token',
applicationName: 'MyMobileApp',
deploymentEnvironment: 'production',
debug: false,
});
// Advanced setup with a custom beacon, disk buffering, and global attributes
SplunkRum.init({
beaconEndpoint: 'https://ingest.example.com/v1/rum',
rumAccessToken: 'your-rum-token',
applicationName: 'MyMobileApp',
allowInsecureBeacon: false,
appStartEnabled: true,
enableDiskBuffering: true,
limitDiskUsageMegabytes: 25,
bufferTimeout: 5000,
bufferSize: 30,
globalAttributes: {
'app.version': '2.3.1',
'build.env': 'release',
},
ignoreUrls: [
'https://analytics.internal.com',
/.*\.healthcheck\.io.*/,
],
});
```
```
--------------------------------
### Manually Finish AppStart Span with SplunkRum.init
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Call `SplunkRum.finishAppStart()` after all initial rendering and data loading is complete. This is necessary when using `SplunkRum.init()` directly, as `OtelWrapper` handles this automatically.
```typescript
import { SplunkRum } from '@splunk/otel-react-native';
// Manual init flow (no OtelWrapper)
SplunkRum.init({
realm: 'us0',
rumAccessToken: 'your-rum-token',
applicationName: 'MyApp',
appStartEnabled: true,
});
async function bootstrap() {
await loadRemoteConfig();
await prefetchCriticalData();
// Signal that the app is fully ready — ends the AppStart span
SplunkRum.finishAppStart();
// AppStart span attributes:
// component: "appstart"
// start.type: "cold" | "warm"
}
bootstrap();
```
--------------------------------
### OtelWrapper
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
A React functional component that wraps your application tree to declaratively initialize the RUM SDK. It automatically calls `SplunkRum.finishAppStart()` when the component mounts, making it a convenient alternative to manual `SplunkRum.init()` calls for static configurations.
```APIDOC
## OtelWrapper — React Component Initializer
A React functional component that wraps the application tree to initialize the RUM SDK declaratively and automatically call `SplunkRum.finishAppStart()` when the component mounts. Preferred over calling `SplunkRum.init()` manually when the configuration is static.
### Parameters
- **configuration** (ReactNativeConfiguration) - Required - An object containing the RUM SDK configuration, including `realm`, `rumAccessToken`, `applicationName`, `deploymentEnvironment`, and optional `globalAttributes`.
### Request Example
```tsx
import React from 'react';
import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { OtelWrapper, startNavigationTracking } from '@splunk/otel-react-native';
import type { ReactNativeConfiguration } from '@splunk/otel-react-native';
const RumConfig: ReactNativeConfiguration = {
realm: 'us0',
rumAccessToken: 'your-rum-token',
applicationName: 'MyApp',
deploymentEnvironment: 'production',
globalAttributes: { 'app.version': '1.0.0' },
};
const Stack = createNativeStackNavigator();
export default function App() {
const navigationRef = useNavigationContainerRef();
return (
// OtelWrapper initializes SplunkRum and ends the AppStart span on mount
{
startNavigationTracking(navigationRef);
}}
>
);
}
```
```
--------------------------------
### startNavigationTracking
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Hooks into a react-navigation NavigationContainer ref to automatically emit OpenTelemetry spans for screen changes. Supports react-navigation v5 and v6. Each navigation event creates a 'Created' span with relevant screen attributes.
```APIDOC
## startNavigationTracking
### Description
Automatically emits OpenTelemetry spans for screen navigation events within a `react-navigation` `NavigationContainer`. This function supports `react-navigation` versions 5 and 6, creating `Created` spans with attributes like `component: ui`, `screen.name`, and `last.screen.name`.
### Usage
```tsx
import React from 'react';
import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native';
import { startNavigationTracking } from '@splunk/otel-react-native';
export default function App() {
const navigationRef = useNavigationContainerRef();
return (
{
// Begin tracking — fires a span for the initial screen immediately
startNavigationTracking(navigationRef);
}}
>
{/* navigator content */}
);
}
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
None
### Resulting Spans
- Span name: "Created"
- Attributes:
- component: "ui"
- screen.name: "[current-screen-name]"
- last.screen.name: "[previous-screen-name]"
- splunk.rumSessionId: ""
```
--------------------------------
### Configure CMake Build for React Native App
Source: https://github.com/hyperdxio/hyperdx-otel-react-native/blob/main/example/android/app/src/main/jni/CMakeLists.txt
Sets the minimum CMake version and project name. Includes React Native utility scripts for building applications with the New Architecture.
```cmake
cmake_minimum_required(VERSION 3.13)
# Define the library name here.
project(splunkotelreactnativeexample_appmodules)
# This file includes all the necessary to let you build your application with the New Architecture.
include(${REACT_ANDROID_DIR}/cmake-utils/ReactNative-application.cmake)
```
--------------------------------
### Initialize Splunk RUM in React Native App
Source: https://github.com/hyperdxio/hyperdx-otel-react-native/blob/main/README.md
Initialize the Splunk RUM library early in your app's lifecycle. Configure with your realm, application name, and RUM access token.
```javascript
import { SplunkRum } from '@splunk/otel-react-native';
const Rum = SplunkRum.init({
realm: 'us0',
applicationName: 'reactNativeTest',
rumAccessToken: 'token',
});
```
--------------------------------
### Custom Spans with OpenTelemetry API
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Utilize the standard OpenTelemetry API (`@opentelemetry/api`) to create custom spans, nested spans with context propagation, and workflow spans with business-level attributes. The SDK registers a global `WebTracerProvider` for this purpose.
```APIDOC
## Custom Spans with OpenTelemetry API
### Description
The SDK registers a global `WebTracerProvider`, so the standard OpenTelemetry API (`@opentelemetry/api`) can be used directly to create custom spans, nested spans with context propagation, and workflow spans with business-level attributes.
### Usage
```ts
import { trace, context } from '@opentelemetry/api';
import { SplunkRum } from '@splunk/otel-react-native';
const tracer = trace.getTracer('checkout');
async function handleCheckout(cart: { items: string[]; total: number }) {
// Parent span representing the full checkout workflow
const checkoutSpan = tracer.startSpan('checkout', {
attributes: {
'component': 'user-interaction',
'workflow.name': 'CHECKOUT',
'cart.item_count': cart.items.length,
'cart.total': cart.total,
},
});
const ctx = trace.setSpan(context.active(), checkoutSpan);
try {
await context.with(ctx, async () => {
// Child span — HTTP fetch is also auto-instrumented within this context
const paymentSpan = tracer.startSpan('process_payment');
paymentSpan.setAttribute('payment.method', 'credit_card');
try {
await fetch('https://api.example.com/payments', {
method: 'POST',
body: JSON.stringify({ total: cart.total }),
});
paymentSpan.setAttribute('payment.status', 'success');
} catch (err) {
paymentSpan.setAttribute('payment.status', 'failed');
SplunkRum.reportError(err, false);
} finally {
paymentSpan.end();
}
});
} finally {
checkoutSpan.end();
}
}
```
```
--------------------------------
### Create Custom Spans with OpenTelemetry API
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Use the standard OpenTelemetry API (`@opentelemetry/api`) to create custom and nested spans. Ensure spans are ended correctly, and errors are reported using `SplunkRum.reportError`.
```typescript
import { trace, context } from '@opentelemetry/api';
import { SplunkRum } from '@splunk/otel-react-native';
const tracer = trace.getTracer('checkout');
async function handleCheckout(cart: { items: string[]; total: number }) {
// Parent span representing the full checkout workflow
const checkoutSpan = tracer.startSpan('checkout', {
attributes: {
'component': 'user-interaction',
'workflow.name': 'CHECKOUT',
'cart.item_count': cart.items.length,
'cart.total': cart.total,
},
});
const ctx = trace.setSpan(context.active(), checkoutSpan);
try {
await context.with(ctx, async () => {
// Child span — HTTP fetch is also auto-instrumented within this context
const paymentSpan = tracer.startSpan('process_payment');
paymentSpan.setAttribute('payment.method', 'credit_card');
try {
await fetch('https://api.example.com/payments', {
method: 'POST',
body: JSON.stringify({ total: cart.total }),
});
paymentSpan.setAttribute('payment.status', 'success');
} catch (err) {
paymentSpan.setAttribute('payment.status', 'failed');
SplunkRum.reportError(err, false);
} finally {
paymentSpan.end();
}
});
} finally {
checkoutSpan.end();
}
}
```
--------------------------------
### Configure Metro for React Native < 0.68
Source: https://github.com/hyperdxio/hyperdx-otel-react-native/blob/main/README.md
Modify metro.config.js to force metro to use browser-specific packages for React Native versions below 0.68. This ensures compatibility with OpenTelemetry.
```javascript
const defaultResolver = require('metro-resolver');
module.exports = {
resolver: {
resolveRequest: (context, realModuleName, platform, moduleName) => {
const resolved = defaultResolver.resolve(
{
...context,
resolveRequest: null,
},
moduleName,
platform,
);
if (
resolved.type === 'sourceFile' &&
resolved.filePath.includes('@opentelemetry')
) {
resolved.filePath = resolved.filePath.replace(
'platform\node',
'platform\browser',
);
return resolved;
}
return resolved;
},
},
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
```
--------------------------------
### Metro Configuration for React Native < 0.68
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Configure Metro to resolve browser-specific OpenTelemetry packages instead of Node.js ones for React Native versions below 0.68. This ensures compatibility with React Native's JavaScript engine.
```javascript
// metro.config.js
const defaultResolver = require('metro-resolver');
module.exports = {
resolver: {
resolveRequest: (context, realModuleName, platform, moduleName) => {
const resolved = defaultResolver.resolve(
{ ...context, resolveRequest: null },
moduleName,
platform
);
// Redirect OpenTelemetry Node platform files to browser platform files
if (
resolved.type === 'sourceFile' &&
resolved.filePath.includes('@opentelemetry')
) {
resolved.filePath = resolved.filePath.replace(
'platform\node',
'platform\browser'
);
return resolved;
}
return resolved;
},
},
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
```
--------------------------------
### SplunkRum.updateLocation
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Sets `location.lat` and `location.long` as global attributes for all subsequent spans, effectively attaching the user's geographic position.
```APIDOC
## SplunkRum.updateLocation
### Description
Updates the global attributes to include the user's current geographic coordinates, setting `location.lat` and `location.long`. This function is a convenience wrapper around `SplunkRum.setGlobalAttributes` using Splunk-specific attribute names.
### Usage
```ts
import { SplunkRum } from '@splunk/otel-react-native';
import Geolocation from '@react-native-community/geolocation';
function startLocationTracking() {
Geolocation.watchPosition(
(position) => {
SplunkRum.updateLocation(
position.coords.latitude,
position.coords.longitude
);
},
(error) => {
SplunkRum.reportError(error, false);
},
{ enableHighAccuracy: true, distanceFilter: 50 }
);
}
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
None
### Global Attributes Example
- `location.lat`: 37.7749
- `location.long`: -122.4194
```
--------------------------------
### SplunkRum.setGlobalAttributes
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Merges the provided key-value pairs into the global attribute set that is appended to every span emitted after the call. Updates are propagated to the native SDK layer.
```APIDOC
## SplunkRum.setGlobalAttributes
### Description
Attaches key-value attributes to all subsequent OpenTelemetry spans. This function merges the provided attributes with the existing global set and also updates the native SDK layer, ensuring that crash reports include the latest attributes.
### Usage
```ts
import { SplunkRum } from '@splunk/otel-react-native';
// Set attributes after user authentication
function onUserLogin(user: { id: string; plan: string }) {
SplunkRum.setGlobalAttributes({
'user.id': user.id,
'user.plan': user.plan,
'session.authenticated': true,
});
}
// Clear sensitive attributes on logout
function onUserLogout() {
SplunkRum.setGlobalAttributes({
'user.id': '',
'user.plan': '',
'session.authenticated': false,
});
}
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
None
### Global Attributes Example
After `onUserLogin()`:
- `user.id`: "usr_abc123"
- `user.plan`: "premium"
- `session.authenticated`: `true`
- `splunk.rumSessionId`: ""
- `screen.name`: ""
```
--------------------------------
### SplunkRum.reportError
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Manually reports a JavaScript error as an OpenTelemetry span with the `component: error` attribute. Useful for caught errors that would not be captured by the automatic global error handler.
```APIDOC
## SplunkRum.reportError
### Description
Manually reports a JavaScript error as an OpenTelemetry span. This is useful for handling caught exceptions that the automatic global error handler might miss. The span includes `exception.message`, `exception.object`, `exception.stacktrace` (truncated), and `exception.isFatal` attributes.
### Usage
```ts
import { SplunkRum } from '@splunk/otel-react-native';
try {
// Code that might throw an error
criticalSetup();
} catch (error) {
// Report a fatal error explicitly
SplunkRum.reportError(error, true);
}
// Or for non-fatal caught errors:
try {
const response = await fetch(...);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: Failed to load user`);
}
} catch (error) {
// Report caught error manually; isFatal=false (default)
SplunkRum.reportError(error);
}
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
None
### Error Reporting Details
- `error` (Error): The JavaScript error object to report.
- `isFatal` (boolean, optional): Indicates if the error is fatal. Defaults to `false`.
### Resulting Span Attributes
- `exception.message`: "[Error message]"
- `exception.object`: "[Error type, e.g., TypeError]"
- `exception.stacktrace`: "[Truncated stack trace]"
- `exception.isFatal`: `true` or `false`
- `component`: "error"
```
--------------------------------
### Manually Report JavaScript Errors
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Manually reports caught JavaScript errors as OpenTelemetry spans. Useful for errors not automatically captured by global handlers. Set the second argument to `true` for fatal errors.
```ts
import { SplunkRum } from '@splunk/otel-react-native';
async function loadUserData(userId: string) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: Failed to load user ${userId}`);
}
return await response.json();
} catch (error) {
// Report caught error manually; isFatal=false (default)
SplunkRum.reportError(error, false);
return null;
}
}
// Report a fatal error explicitly
try {
criticalSetup();
} catch (error) {
SplunkRum.reportError(error, true);
// Resulting span attributes:
// exception.message: "criticalSetup is not a function"
// exception.object: "TypeError"
// exception.stacktrace: "TypeError: criticalSetup is not a function\n at ..."
// exception.isFatal: true
// component: "error"
}
```
--------------------------------
### Set Global Attributes for All Spans
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Merges provided key-value pairs into the global attribute set, appended to all subsequent spans. Updates are propagated to the native SDK for crash reports.
```ts
import { SplunkRum } from '@splunk/otel-react-native';
// Set attributes after user authentication
function onUserLogin(user: { id: string; plan: string }) {
SplunkRum.setGlobalAttributes({
'user.id': user.id,
'user.plan': user.plan,
'session.authenticated': true,
});
}
// Clear sensitive attributes on logout
function onUserLogout() {
SplunkRum.setGlobalAttributes({
'user.id': '',
'user.plan': '',
'session.authenticated': false,
});
}
// All spans created after onUserLogin() will carry:
// user.id: "usr_abc123"
// user.plan: "premium"
// session.authenticated: true
// splunk.rumSessionId: ""
// screen.name: ""
```
--------------------------------
### Update Location for Spans
Source: https://context7.com/hyperdxio/hyperdx-otel-react-native/llms.txt
Sets `location.lat` and `location.long` as global attributes for all subsequent spans. This function wraps `setGlobalAttributes` with Splunk-specific attribute names.
```ts
import { SplunkRum } from '@splunk/otel-react-native';
import Geolocation from '@react-native-community/geolocation';
function startLocationTracking() {
Geolocation.watchPosition(
(position) => {
SplunkRum.updateLocation(
position.coords.latitude,
position.coords.longitude
);
// All subsequent spans include:
// location.lat: 37.7749
// location.long: -122.4194
},
(error) => {
SplunkRum.reportError(error, false);
},
{ enableHighAccuracy: true, distanceFilter: 50 }
);
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.