npm package: @plushanalytics/react-native-session-replay
Description: React Native SDK for Plush Analytics events + session replay ingestion.
Author: Plush Analytics
Latest version: 3.0.7

# @plushanalytics/react-native-session-replay

React Native SDK for Plush Analytics (events + session replay) with a React Provider/hook.

Under the hood, this SDK also uses posthog's MIT opensource implementations. 

## Install

```bash
npm install @plushanalytics/react-native-session-replay
```

> [!NOTE]
> This package includes native code and is not compatible with Expo Go. Use development builds:

```bash
npx expo run:ios
npx expo run:android
```

## Quick Setup (Provider + Hook)

```tsx
import React from "react";
import { Button } from "react-native";
import { PlushAnalyticsProvider, usePlushAnalytics } from "@plushanalytics/react-native-session-replay";

function CheckoutButton(): JSX.Element {
  const analytics = usePlushAnalytics();
  return (
    <Button
      title="Purchase"
      onPress={() => {
        void analytics.track("purchase_clicked", { properties: { plan: "pro" } });
      }}
    />
  );
}

export default function App(): JSX.Element {
  return (
    <PlushAnalyticsProvider
      config={{
        apiKey: "plsh_live_...",
        projectId: "mobile_app",
        context: { platform: "react-native" },
        sessionReplayConfig: {
          enabled: true,
          masking: {
            textInputs: true,
            images: true,
            sandboxedViews: true,
          },
          captureNetworkTelemetry: true,
          throttleDelayMs: 1000,
        },
      }}
    >
      <CheckoutButton />
    </PlushAnalyticsProvider>
  );
}
```

## Direct Client Usage (No React)

```ts
import { createPlushAnalyticsClient } from "@plushanalytics/react-native-session-replay";

const analytics = createPlushAnalyticsClient({
  apiKey: "<Your-api-key>",
  projectId: "<Your-project-id>",
  sessionReplayConfig: {
    enabled: true,
    masking: {
      textInputs: false,
      images: false,
      sandboxedViews: false,
    },
  },
});

await analytics.track("app_opened");
await analytics.shutdown();
```

## Session Replay Config

Replay behavior is configured locally in the SDK.

- `config.sessionReplayConfig.enabled`: defaults to `true`
- `config.sessionReplayConfig.masking.textInputs`: defaults to `true`
- `config.sessionReplayConfig.masking.images`: defaults to `true`
- `config.sessionReplayConfig.masking.sandboxedViews`: defaults to `true`
- `config.sessionReplayConfig.captureLog`: defaults to `true`
- `config.sessionReplayConfig.captureNetworkTelemetry`: defaults to `true`
- `config.sessionReplayConfig.throttleDelayMs`: defaults to `1000`

Per-session overrides are supported via `startSessionRecording({ replayConfig })` / `startReplay({ replayConfig })`.

```ts
await analytics.startReplay({
  replayConfig: {
    enabled: true,
    masking: {
      images: false,
    },
  },
});
```

Legacy flat replay keys are still supported in per-session overrides for backward compatibility:
`maskAllTextInputs`, `maskAllImages`, `maskAllSandboxedViews`.

## Replay Authentication Headers

Replay uploads include these headers from the configured `apiKey`:

- `x-api-key`
- `x-plush-api-key`
- `x-plushanalytics-key`
- `Authorization: Bearer <apiKey>`

Headers are injected natively on outgoing replay batch requests so they remain present even if underlying SDK session defaults are rewritten.

## Common Usage / Examples

### Basic Event Tracking
```ts
// Track a simple event
await analytics.track("app_opened");

// Track with properties and explicitly override the source context
await analytics.track("cta_clicked", { 
  properties: { plan: "pro", button_color: "blue", flow: "onboarding" },
  source: "mobile_app"
});
```

### Complex Events with Massive Payloads

The `properties` and `context` fields support arbitrary, deeply nested `JsonValue` objects. You can attach massive amounts of unstructured metadata directly to an event:

```ts
await analytics.track("checkout_completed", {
  properties: {
    cart_id: "192381923",
    total: 249.99,
    currency: "USD",
    items: [
      { id: "sku_1", name: "Premium Widget", category: "Hardware", price: 199.99 },
      { id: "sku_2", name: "Extended Warranty", category: "Services", price: 50.00 }
    ],
    discounts_applied: [{ code: "SUMMER", amount: 10.0 }],
    ab_test_variants: {
      checkout_ui: "v2_minimal",
      button_color: "green"
    }
  },
  context: {
    device: {
      battery_level: 42,
      thermal_state: "nominal",
      storage_free_mb: 10243
    },
    network: {
      type: "wifi",
      speed_mbps: 150
    },
    custom_metadata: {
      active_timers: ["session", "checkout"],
      redux_state_hash: "abcd1234efgh"
    }
  },
  source: "web_storefront",
  timestamp: new Date().toISOString() // Optionally override the exact event time
});
```

### User Identification & Grouping
```ts
// Tie events to a specific user
await analytics.identify("user_123", { 
  traits: { plan: "pro", email: "user@example.com" } 
});

// Tie events to an organization or group
await analytics.group("org_456", { 
  traits: { tier: "enterprise", industry: "crypto" } 
});
```

### Screen Tracking & Context
```ts
// Track screen views
await analytics.screen("Settings", { 
  properties: { tab: "billing" } 
});

// Set global context automatically appended to all future events
analytics.setContext({ build: 42, app_version: "2.1.0" });
```

### Session Replay Lifecycle
```ts
// Start recording manually (usually handled automatically by Provider)
await analytics.startSessionRecording({
  replayConfig: {
    masking: { textInputs: true, images: true }
  }
});

// Force flush the current recording buffer to the network
await analytics.flushSessionRecording();

// Stop the recording (e.g. when the user logs out)
await analytics.stopSessionRecording();
```

### Buffer Management
```ts
// Force upload all queued events and replays immediately
await analytics.flush();

// Clear the queue and reset the client state (e.g. on logout)
await analytics.reset();

// Shut down all background timers completely 
await analytics.shutdown();
```

## Advanced Escape Hatch (`analytics.plush`)

The standard wrapper methods (`track`, `identify`, `startSessionRecording`, etc.) should be used as the primary API for lifecycle safety and compatibility.

If you need advanced capabilities not exposed by the wrapper, you can access the full underlying Core Analytics Client instance via the `analytics.plush` property. This escape hatch is officially supported and can be strongly typed:

```tsx
import type { PlushAnalyticsClient } from "@plushanalytics/javascript";

// Typing the escape hatch instance explicitly
const analytics = usePlushAnalytics<PlushAnalyticsClient>();

// The standardized wrapper methods are still available
await analytics.track("purchase");

// Advanced underlying methods are accessible via `.plush`. 
// Note: Rely on `.track()`, and avoid the legacy `.trackEvent()` method
await analytics.plush.track("purchase_advanced", { source: "mobile_app", properties: { item: "subscription" } });
```

## Manual Masking (`PlushMaskView`)

If you want to manually mask specific React Native elements from session replays, wrap them in the `<PlushMaskView>` component instead of waiting for the global config to catch them.

```tsx
import { PlushMaskView } from "@plushanalytics/react-native-session-replay";

function SensitiveComponent() {
  return (
    <PlushMaskView>
      <Text>This text is completely hidden in replays!</Text>
    </PlushMaskView>
  );
}
```

*Note: You can also just apply `accessibilityLabel="ph-no-capture"` instead of `<PlushMaskView>` directly to any React Native `View` or `Text` block you want to hide.*

## API Surface

The SDK exports the following core primitives:

### Components & React
- `PlushAnalyticsProvider` - Wraps your app to inject and manage the client lifecycle.
- `usePlushAnalytics()` - Returns the active `PlushAnalytics` client.
- `PlushMaskView` - React component to manually mask children from replays.

### Client Factory
- `createPlushAnalyticsClient(config: PlushAnalyticsConfig)` - Factory to create the pure JS client.

### Core Types
- `PlushAnalytics` - The main client interface returned by the hook and factory.
- `PlushAnalyticsConfig` - Configuration payload for `createPlushAnalyticsClient`.
- `SessionRecordingOptions` & `SessionReplayConfig` - Typings for replay behavior.
- `TrackOptions`, `IdentifyOptions`, `GroupOptions`, `ScreenOptions` - Options for event tracking calls.