## Overview

The [Coralogix React Native Plugin](https://www.npmjs.com/package/@coralogix/react-native-plugin) is the latest and recommended SDK for enabling [Real User Monitoring](https://coralogix.com/docs/user-guides/rum/getting-started/real-user-monitoring/index.md) (RUM) in React Native applications. This plugin replaces the legacy `@coralogix/react-native-sdk` and provides a more stable, high-performance integration.

## Prerequisites

- Deploy our [RUM Integration Package](https://coralogix.com/docs/user-guides/rum/getting-started/rum-integration-package/index.md). This includes creating your RUM API key, which is required for the SDK setup.
- Add `react-native-url-polyfill` at your app's entry point. The plugin needs `URL` to be available globally:

```js
// index.js
import 'react-native-url-polyfill/auto';

import { AppRegistry } from 'react-native';
import App from './App';
// ...
```

## Usage

To use the Coralogix SDK, call `CoralogixRum.init(options)` at the earliest possible moment after the page load. This will initialize the SDK based on the options you provided.

```js
import { CoralogixRum } from '@coralogix/react-native-plugin';

CoralogixRum.init({
  application: 'app-name',
  environment: 'production',
  public_key: 'abc-123-456',
  coralogixDomain: 'EU2',
  version: 'v1.0.3',
  labels: {
    payment: 'visa',
  },
  ignoreErrors: ['some error message to ignore'],
  sessionSampleRate: 100 // Percentage of overall sessions being tracked, Default to 100%
});
```

These fields configure various aspects of the Coralogix RUM SDK, including identification, environment settings, error handling, and data tagging in the `CoralogixRum.init()` function:

| Field Name         | Description                                                                                                                                                | Example Value                                                             |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| application        | The name of the application being monitored.                                                                                                               | 'app-name'                                                                |
| environment        | The environment in which the application is running (e.g., production, staging, development).                                                              | 'production'                                                              |
| public_key         | The public API key used for authentication with Coralogix.                                                                                                 | 'abc-123-456'                                                             |
| coralogixDomain    | The [Coralogix domain](https://coralogix.com/docs/user-guides/account-management/account-settings/coralogix-domain/index.md) associated with your account. | 'EU2'                                                                     |
| version            | The version of the application being monitored.                                                                                                            | 'v1.0.3'                                                                  |
| labels             | Custom labels to tag and categorize data being sent.                                                                                                       | { payment: 'visa' }                                                       |
| ignoreErrors       | A list of error messages or patterns to be ignored by the monitoring system.                                                                               | ['some error message to ignore']                                          |
| sessionSampleRate  | The percentage of sessions to be tracked by the monitoring system. A value of 100 means all sessions.                                                      | 100                                                                       |
| ignoreUrls         | A list of URLs (strings or regex patterns) to exclude from tracing.                                                                                        | `['https://example.com/health', /\\.svg$/]`                               |
| collectIPData      | Send the client IP for region detection. Defaults to `true`.                                                                                               | `true`                                                                    |
| debug              | Turns on internal debug logging.                                                                                                                           | `false`                                                                   |
| networkExtraConfig | Per-URL rules for capturing request and response headers and payloads. See [Network capture rules](#network-capture-rules).                                | `[{ urlPattern: 'https://api.example.com/.*', collectReqPayload: true }]` |

Use the exported functions of CoralogixRum to provide contextual information or transmit manual logs. Remember, these functions will remain inactive until you invoke `CoralogixRum.init()`.

```js
import { CoralogixRum } from '@coralogix/react-native-plugin';

// Update user context dynamically
CoralogixRum.setUserContext({
  user_id: '123',
  user_name: 'name',
  user_email: 'user@email.com',
  user_metadata: {
    role: 'admin',
    // ...
  }
});

// Update custom labels dynamically
CoralogixRum.setLabels({
  ...CoralogixRum.getLabels(),
  paymentMethod: 'visa',
  userTheme: 'dark',
  // ...
});

// Update application context dynamically
CoralogixRum.setApplicationContext({
  application: 'app-name',
  version: '1.0.0'
});

CoralogixRum.log(CoralogixLogSeverity.Error, 'this is a log', { key: 'value' });
CoralogixRum.error('this is a log with error severity', { key: 'value' });
```

## Instrumentation

You can enable or disable specific instrumentation, with the default set to all trues. Each instrumentation controls the data the SDK will track and collect.

```js
CoralogixRum.init({
  // ...
  instrumentations: {
    errors: true,
    custom: true,
    mobile_vitals: true,
    anr: true,
    lifecycle: true,
    user_interaction: true,
    network: true
  }
});
```

## Features

### Session Replay

Record and replay user sessions to visually inspect user behavior leading up to errors, performance issues, or unexpected interactions. Session replay for React Native is disabled by default and must be explicitly enabled.

Learn how to enable and configure session replay in [**Enable Session Replay for React Native**](https://coralogix.com/docs/user-guides/rum/product-features/session-replay/react-native/index.md).

### Mobile Vitals

Automatically collects key app performance metrics, including **CPU**, **memory**, **FPS**, **cold start**, **warm start**, and **ANR** events.\
These metrics are aggregated and sent every 15 seconds.\
Learn more about collected metrics and analysis workflows in [**Mobile Vitals**](https://coralogix.com/docs/user-guides/rum/product-features/mobile-performance/index.md).

#### Configure Mobile Vitals

```React
// Add this to CoralogixRum.init(...)
CoralogixRum.init({
  // ...
  mobileVitals: {
    warm: true,
    cold: true,
    cpu: true,
    memory: true,
    rendering: true,        // FPS / rendering
    slowFrozenFrames: true
  }
});
```

| Key                | Controls                              |
| ------------------ | ------------------------------------- |
| `warm`             | Warm start duration                   |
| `cold`             | Cold start duration                   |
| `cpu`              | CPU usage and main-thread time deltas |
| `memory`           | Memory footprint / utilization        |
| `rendering`        | FPS (rendering performance)           |
| `slowFrozenFrames` | Slow/frozen frame counts              |

### Ignore specific errors

The `ignoreErrors` option lets you exclude errors that meet specific criteria. This option accepts strings and regular expressions to match against the event's error message. Use regular expressions for exact matches, as strings remove partial matches.

```js
import { CoralogixRum } from '@coralogix/react-native-plugin';

CoralogixRum.init({
  // ...
  ignoreErrors: [/Exact Match Error Message/, 'partial/match'],
});
```

### Propagate trace context

Add trace context propagation in headers across service boundaries.

```js
CoralogixRum.init({
  // ...
  traceParentInHeader: {
    enabled: true
  },
});
```

### Modify events before sending

Enable event access and modification before sending to Coralogix, allowing content modification and event discarding.

```js
CoralogixRum.init({
  // ...
  beforeSend: (event) => {
    // Discard events from @company.com users.
    if (event.session_context.user_email?.endsWith('@company.com')) {
      return null;
    }

    // Redact sensitive information from the page URL.
    event.page_context.page_url = event.page_context.page_url.replace(
      'sensitive-info',
      'redacted'
    );

    return event;
  },
});
```

### Network capture rules

By default, the SDK captures request URLs, status codes, and timings. Use `networkExtraConfig` in `CoralogixRum.init()` to capture specific request and response headers or payloads on a per-URL basis.

```js
CoralogixRum.init({
  // ...
  networkExtraConfig: [
    {
      urlPattern: 'https://api.example.com/.*',
      reqHeaders: ['X-Request-Id'],
      resHeaders: ['X-Response-Time'],
      collectReqPayload: true,
      collectResPayload: false,
    },
  ],
});
```

| `NetworkCaptureRule` field | Description                                                  |
| -------------------------- | ------------------------------------------------------------ |
| `urlPattern`               | Regex pattern that matches request URLs the rule applies to. |
| `reqHeaders`               | Array of request header names to capture.                    |
| `resHeaders`               | Array of response header names to capture.                   |
| `collectReqPayload`        | When `true`, capture the request body.                       |
| `collectResPayload`        | When `true`, capture the response body.                      |

### Route data through a proxy

Proxy configuration to route requests. Specifying a proxy URL will direct all RUM data to this URL via the POST method. Ensure this data is subsequently relayed from the proxy to Coralogix. The Coralogix route for each request sent to the proxy is available in the request’s `cxforward` parameter (for example, `https://www.your-proxy.com/endpoint?cxforward=https%3A%2F%2Fingress.eu1.rum-ingress-coralogix.com%2Fbrowser%2Fv1beta%2Flogs`).

```js
CoralogixRum.init({
  // ...
  coralogixDomain: 'EU1',
  proxyUrl: '<https://www.your-proxy.com/endpoint>'
});
```

## View tracking with React Navigation

The plugin ships a turn-key helper that wires into a React Navigation navigator. Pass your `NavigationContainer`'s ref to `attachReactNavigationObserver` to record view changes automatically.

```jsx
import {
  NavigationContainer,
  createNavigationContainerRef,
} from '@react-navigation/native';
import { attachReactNavigationObserver } from '@coralogix/react-native-plugin';

const navigationRef = createNavigationContainerRef();

export default function App() {
  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() => attachReactNavigationObserver(navigationRef)}
      onStateChange={() => attachReactNavigationObserver(navigationRef)}
    >
      {/* ... */}
    </NavigationContainer>
  );
}
```

The helper calls `CoralogixRum.setViewContext()` whenever the active route changes, so each replay frame and span is tagged with the correct view name.

## Utility methods

Inspect SDK state or update context at runtime. The plugin's `init` is async; some helpers are synchronous accessors after initialization completes.

```js
import { CoralogixRum } from '@coralogix/react-native-plugin';

// Confirm the SDK is initialized.
const initialized = CoralogixRum.isInited;

// Read the current session ID.
const sessionId = await CoralogixRum.getSessionId();

// Read the current user context or labels.
const user = CoralogixRum.getUserContext();
const labels = CoralogixRum.getLabels();

// Update the application context after init.
CoralogixRum.setApplicationContext({ application: 'my-app', version: '1.2.0' });
```

### Log severity shorthand methods

The plugin exposes shorthand methods for each log severity in addition to the full `log(severity, message, data, labels)` form:

```js
CoralogixRum.debug('debug message');
CoralogixRum.verbose('verbose message');
CoralogixRum.info('info message');
CoralogixRum.warn('warn message');
CoralogixRum.error('error message', { context: 'value' });
CoralogixRum.critical('critical message');
```

## Support

**Need help?**

Our world-class customer success team is available 24/7 to assist you with your setup and answer any questions you may have.

Feel free to reach out to us **via our in-app chat** or by emailing [support@coralogix.com](mailto:support@coralogix.com).
