# Official Coralogix SDK for React Native

[![npm version](https://img.shields.io/npm/v/@coralogix/react-native-sdk.svg)](https://www.npmjs.com/package/@coralogix/react-native-sdk)

** Note: SDK for React Native is currently in Beta **

## Links

- [Coralogix Real User Monitoring](https://coralogix.com/docs/real-user-monitoring/)

## Usage

To use Coralogix SDK, call `CoralogixRum.init(options)` at the soonest available moment after the app loads.
This will initialize the SDK based on the options you provided.

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

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%
});
```

To provide contextual information or transmit manual logs, utilize the exported functions of `CoralogixRum`.
Keep in mind that these functions will remain inactive until you've invoked `CoralogixRum.init()`.

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

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

### View Tracking

To track views, set the view context whenever a view changes.

```javascript
CoralogixRum.setViewContext({
  view: 'Home',
});
```

You can automatically track view changes by using [react-navigation](https://reactnavigation.org/docs/navigation-container/#onstatechange).

```javascript
<NavigationContainer
  ref={navigationRef}
  onStateChange={() => {
    const currentRouteName = navigationRef.current.getCurrentRoute().name;

    CoralogixRum.setViewContext({ view: currentRouteName });
  }}
>
  >{/* ... */}
</NavigationContainer>
```

### Instrumentation's

Turn on/off specific instrumentation, default to all trues.
Each instrumentation is responsible for which data the SDK will track and collect for you.

```javascript
CoralogixRum.init({
  // ...
  instrumentations: {
    fetch: false,
    custom: true,
    errors: true,
  },
});
```

### Ignore Errors

The ignoreErrors option allows you to exclude errors that meet specific criteria.
This options accepts a set of strings and regular expressions to match against the event's error message.
Use regular expressions for exact matching as strings remove partial matches.

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

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

### TraceParentInHeader

Add trace context propagation in headers across service boundaries

```javascript
CoralogixRum.init({
  // ...
  traceParentInHeader: {
    enabled: true,
    options: {
      // When the backend domain is different from the app domain, specifying backend domains is necessary.
      propagateTraceHeaderCorsUrls: [new RegExp('https://webapi.*')],
      // B3 propagation
      propagateB3TraceHeader: {
        singleHeader: true,
        multiHeader: true,
      },
      // Aws propagation
      propagateAwsXrayTraceHeader: true,
    },
  },
});
```

### beforeSend

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

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

    // Redact sensitive information.
    event.session_context.user_email = '***@***';

    return event;
  },
});
```

### Proxy Url

Proxy configuration to route requests.  
By specifying a proxy URL, all RUM data will be directed to this URL via the POST method.
However, it is necessary for this data to be subsequently relayed from the proxy to Coralogix.
The Coralogix route for each request that is 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).

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

### Troubleshooting

#### URL.origin is not implemented

1. `npm install react-native-url-polyfill`
2. At the top of your entry-point file (index.js) add:
   `import "react-native-url-polyfill/auto"`

---

## 🔒 SSL Pinning (react-native-ssl-pinning)

---

**Initialize the SDK:**

> ✅ **Important:** When SSL pinning is enabled (`sslFetch: true`), the regular `fetch` instrumentation **must be disabled** to avoid conflicts.

```javascript
CoralogixRum.init({
  debug: true,
  instrumentations: {
    fetch: false, // Disable regular fetch instrumentation
    sslFetch: true, // Enable SSL pinning fetch instrumentation
  },
});
```

---

### Android Setup

1. **Modify `android/app/build.gradle`:**

   - At the **top of the file**, add:

     ```groovy
     apply from: "../../node_modules/@coralogix/react-native-sdk/ssl/android/preBuildSetup.gradle"
     ```

   - Inside the `android {}` block, add:
     ```groovy
     sourceSets {
       main {
         java.srcDirs += ['../../node_modules/@coralogix/react-native-sdk/ssl/android']
       }
     }
     ```

2. **Update `MainApplication.java`:**

   - Add import:

     ```java
     import com.coralogix.reactnativesdk.ssl.OkHttp3InterceptorPackage;
     ```

   - Add `OkHttp3InterceptorPackage` to the package list:
     ```java
            override fun getPackages(): List<ReactPackage> =
            PackageList(this).packages.apply {
                add(OkHttp3InterceptorPackage())
            }
     ```

---

### iOS Setup

1. **Add Files in Xcode:**

   - Open `ios/YourProject.xcworkspace` in Xcode.
   - Go to **File > Add Files to "YourProject"...**
   - Add all files from:
     ```
     node_modules/@coralogix/react-native-sdk/ssl/ios
     ```
     (includes `NetworkInterceptor.h/.m`, `NetworkInterceptorEmitter.h/.m`)

2. **Install Dependencies:**
   ```
   cd ios && pod install
   ```
