# React Native plugin

Copy as Markdown[Open in ChatGPT](https://chatgpt.com/?q=Read%20https%3A%2F%2Fdocs-docusaurus.kinsta.page%2Fuser-guides%2Frum%2Fsdk-installation%2Freact-native%2Freact-native-plugin.md%20and%20help%20me%20with%20my%20question%20about%20this%20Coralogix%20documentation%20page.)[Open in Claude](https://claude.ai/new?q=Read%20https%3A%2F%2Fdocs-docusaurus.kinsta.page%2Fuser-guides%2Frum%2Fsdk-installation%2Freact-native%2Freact-native-plugin.md%20and%20help%20me%20with%20my%20question%20about%20this%20Coralogix%20documentation%20page.)

## Overview[​](#overview "Direct link to 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://docs-docusaurus.kinsta.page/user-guides/rum/getting-started/real-user-monitoring/.md) (RUM) in React Native applications. This plugin replaces the legacy `@coralogix/react-native-sdk` and provides a more stable, high-performance integration.

## Prerequisites[​](#prerequisites "Direct link to Prerequisites")

* Deploy our [RUM Integration Package](https://docs-docusaurus.kinsta.page/user-guides/rum/getting-started/rum-integration-package/.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:

  ```
  // index.js

  import 'react-native-url-polyfill/auto';



  import { AppRegistry } from 'react-native';

  import App from './App';

  // ...
  ```

## Usage[​](#usage "Direct link to 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.

```
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://docs-docusaurus.kinsta.page/user-guides/account-management/account-settings/coralogix-domain/.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()`.

```
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[​](#instrumentation "Direct link to 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.

```
CoralogixRum.init({

  // ...

  instrumentations: {

    errors: true,

    custom: true,

    mobile_vitals: true,

    anr: true,

    lifecycle: true,

    user_interaction: true,

    network: true

  }

});
```

## Features[​](#features "Direct link to Features")

### Session Replay[​](#session-replay "Direct link to 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://docs-docusaurus.kinsta.page/user-guides/rum/product-features/session-replay/react-native/.md).

### Mobile Vitals[​](#mobile-vitals "Direct link to Mobile Vitals")

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

#### Configure Mobile Vitals[​](#configure-mobile-vitals "Direct link to Configure Mobile Vitals")

```
// 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[​](#ignore-specific-errors "Direct link to 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.

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



CoralogixRum.init({

  // ...

  ignoreErrors: [/Exact Match Error Message/, 'partial/match'],

});
```

### Propagate trace context[​](#propagate-trace-context "Direct link to Propagate trace context")

Add trace context propagation in headers across service boundaries.

```
CoralogixRum.init({

  // ...

  traceParentInHeader: {

    enabled: true

  },

});
```

### Modify events before sending[​](#modify-events-before-sending "Direct link to Modify events before sending")

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

```
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[​](#network-capture-rules "Direct link to 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.

```
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[​](#route-data-through-a-proxy "Direct link to 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`).

```
CoralogixRum.init({

  // ...

  coralogixDomain: 'EU1',

  proxyUrl: '<https://www.your-proxy.com/endpoint>'

});
```

## View tracking with React Navigation[​](#view-tracking-with-react-navigation "Direct link to 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.

```
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[​](#utility-methods "Direct link to Utility methods")

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

```
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[​](#log-severity-shorthand-methods "Direct link to Log severity shorthand methods")

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

```
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');
```
