@bitdrift/react-native

中文文档
0.15.0发布于 2026/10/23SEE LICENSE IN LICENSETypeScriptESM + CJS构建来源已验证近 30 天下载 6万

bitdrift integration for React Native

原始使用文档
文档目录15 节
  1. Installation
  2. Usage
  3. Expo
  4. React Native / Ejected Expo
  5. Spans
  6. Configuration Options
  7. Crash Reporting
  8. Previous Run Info
  9. SDK Status
  10. Start Result Callback
  11. Feature Flag Tracking
  12. Entity Identification
  13. Tracing State
  14. Network Integration
  15. WebView Integration

@bitdrift/react-native

bitdrift integration for React Native

Installation

npm install @bitdrift/react-native

Usage

Expo

If you are using Expo to build your React Native app and don't want to use an ejected workflow, you can use the @bitdrift/react-native package to initialize the Capture library and log messages at different log levels. Note that this initializes the library later than is ideal, but should still provide most of the benefits of using Capture.

import {
  init,
  trace,
  debug,
  info,
  warn,
  error,
  isTracingActive,
  setEntityId,
  clearEntityId,
  startSpan,
  SpanResult,
  SessionStrategy,
} from '@bitdrift/react-native';

init('<api key>', SessionStrategy.Activity, {
  startResult: (result) => {
    console.log('Capture start result', result);
  },
  crashReporting: {
    enableNativeFatalIssues: true, // Enable native crash reporting (crashes, ANRs, etc.)
    UNSTABLE_enableJsErrors: true, // Enable JavaScript error reporting (fatal and non-fatal)
    UNSTABLE_onBeforeReportSend: (report) => {
      // Add your custom handling for report metadata.
      // Available fields: report.reportType, report.sessionId, report.details, report.reason, report.fields
    },
  },
});

info('Hello, World!');
setEntityId('user-123');
console.log('Tracing active?', isTracingActive());
clearEntityId();

const span = startSpan('loading_profile', 'info', { source: 'tap' });
// ... perform the work ...
span?.end(SpanResult.SUCCESS, { cached: false });

For all Expo usages, make sure to add @bitdrift/react-native to the plugins field in your app.json file. This helps ensure setting up the native modules correctly.

{
  "expo": {
    "plugins": [
      "@bitdrift/react-native"
    ]
  }
}

Android-only WebView instrumentation note:

  • UNSTABLE_webViewInstrumentation currently only affects Android app builds.
  • In this package, automatic setup is only provided through the Expo config plugin / generated Android Gradle setup.
  • Non-Expo Android apps can still enable the same instrumentation manually by applying the Gradle plugin and configuring the bitdrift instrumentation block.
  • It does not affect iOS builds.
  • It does not automatically configure non-Expo / vanilla React Native Android projects.

Expo Go

Due to loading native modules, the @bitdrift/react-native package is not supported in Expo Go.

React Native / Ejected Expo

First initialize the Capture library by using the per-platform instructions found here.

For iOS, perform the initialization in didFinishLaunchingWithOptions in your AppDelegate.m file.

-
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

  [CAPLogger startWithAPIKey:@"<api key>" sessionStrategy: CAPSessionStrategy.fixed]];

  ...

For Android, perform the initialization in onCreate in your MainApplication.kt file.

  override fun onCreate() {
    super.onCreate()
    Capture.Logger.start(
      apiKey = "<api key>",
      sessionStrategy = SessionStrategy.Fixed()
    )
    ...
  }

To add custom log messages from your React Native app, import the log level functions from the @bitdrift/react-native package and use them to log messages at the desired log level.

Spans

Use spans to measure an operation with a matched start and end event. startSpan returns null until Capture has been initialized. End each started span once; repeated end calls are ignored.

import { startSpan, SpanResult } from '@bitdrift/react-native';

const parent = startSpan('load_profile', 'info', { profileId: '123' });
const child = startSpan('fetch_profile', 'debug', undefined, undefined, parent?.id);

// ... perform the request ...
child?.end(SpanResult.SUCCESS, { cacheHit: false });
parent?.end(SpanResult.SUCCESS);

startTimeMs and endTimeMs are optional Unix timestamps in milliseconds. If either is used, provide both so Capture can calculate and place the span correctly.

Configuration Options

Crash Reporting

The crashReporting option allows you to configure crash and error reporting behavior:

init('<api key>', SessionStrategy.Activity, {
  crashReporting: {
    enableNativeFatalIssues: true, // Enable native crash reporting (crashes, ANRs, etc.)
    UNSTABLE_enableJsErrors: true, // Enable JavaScript error reporting (fatal and non-fatal)
    UNSTABLE_onBeforeReportSend: (report) => {
      // Add your custom handling for report metadata.
      // Available fields: report.reportType, report.sessionId, report.details, report.reason, report.fields
    },
  }
});
  • enableNativeFatalIssues: When true, enables reporting of native fatal issues including crashes, ANRs (Application Not Responding), and other critical errors. Defaults to true.
  • UNSTABLE_enableJsErrors: When true, enables reporting of JavaScript errors (both fatal and non-fatal) via React Native's global error handler. Captures unhandled exceptions with stack traces. This feature is experimental and may change in future releases. Defaults to false.
  • UNSTABLE_onBeforeReportSend: Called before an issue report is sent. Receives { reportType, reason, details, sessionId, fields }.

Previous Run Info

Use getPreviousRunInfo() to check whether the previous app run ended in a fatal termination.

import {
  getPreviousRunInfo,
  init,
  SessionStrategy,
  type PreviousRunInfo,
} from '@bitdrift/react-native';

init('<api key>', SessionStrategy.Activity);

const previousRunInfo: PreviousRunInfo = getPreviousRunInfo();

if (previousRunInfo?.hasFatallyTerminated) {
  console.log('Previous run terminated fatally', previousRunInfo.terminationReason);
}

PreviousRunInfo shape:

type PreviousRunInfo = {
  hasFatallyTerminated: boolean;
  terminationReason?: string;
} | null;
  • This API is synchronous.
  • Call it after init(...).
  • Android: available on API 30+ (Android 11+); returns null on older versions.
  • iOS simulator: returns null by design; use a physical device to validate.
  • terminationReason is currently populated on Android. iOS currently provides hasFatallyTerminated.

SDK Status

Use getSdkStatus() to inspect the SDK's current initialization state and recent backend activity.

import { getSdkStatus, init, SessionStrategy, type SdkStatus } from '@bitdrift/react-native';

init('<api key>', SessionStrategy.Activity);

const sdkStatus: SdkStatus = getSdkStatus();
console.log(sdkStatus.initializationState);

SdkStatus shape:

type SdkStatus = {
  initializationState: 'notStarted' | 'loaded' | 'running' | 'disabled';
  lastHandshakeTimeMs?: number;
  lastConfigDeliveryTimeMs?: number;
};
  • This API is synchronous.
  • It can be called before or after init(...).
  • When Capture has not started yet, initializationState is notStarted.

Start Result Callback

Use startResult to observe whether native SDK startup succeeded.

import { init, SessionStrategy } from '@bitdrift/react-native';

init('<api key>', SessionStrategy.Activity, {
  startResult: (result) => {
    if (result.success) {
      console.log('Capture started successfully');
    } else {
      console.log('Capture failed to start', result.error);
    }
  },
});

StartResult shape:

type StartResult = {
  success: boolean;
  error?: string;
};
  • The callback is invoked at most once per init(...) call.
  • This callback is experimental and may change.
import { trace, debug, info, warn, error } from '@bitdrift/react-native';

// Log at the desired log level using the different log level functions.

trace('Hello, World!');

debug('Hello, World!');

info('Hello, World!');

warn('Hello, World!');

error('Hello, World!');

// Optionally pass an Error object to automatically capture error details
try {
  // some code that might throw
} catch (err) {
  error('Failed to process request', err);
  // Or with additional fields
  error('Failed to process request', err, { userId: '123' });
}

Feature Flag Tracking

Track feature flag exposures to understand which variants users are seeing:

import { setFeatureFlagExposure } from '@bitdrift/react-native';

// Track string variant
setFeatureFlagExposure('dark_mode', 'enabled');
setFeatureFlagExposure('new_ui', 'variant_b');

// Track boolean variant
setFeatureFlagExposure('experimental_feature', true);
setFeatureFlagExposure('beta_mode', false);

Entity Identification

Sets an entity identifier for backend correlation with device identifier. The value is hashed for storage and the exact value is never persisted.

import { clearEntityId, setEntityId } from '@bitdrift/react-native';

setEntityId('user-123');
setEntityId('account-456');
clearEntityId();

Tracing State

Use isTracingActive() to synchronously check whether trace propagation is currently active.

import { init, isTracingActive, SessionStrategy } from '@bitdrift/react-native';

init('<api key>', SessionStrategy.Activity);

const tracingActive = isTracingActive();
console.log('Tracing active?', tracingActive);
  • It returns false when tracing is not active or the SDK is not running.

Network Integration

The automatic capture of network requests can be achieved in a few different ways depending on the platform and the networking library being used.

iOS

When initializing via JS, pass enableNetworkInstrumentation: true as one of the options to init:

import { init, SessionStrategy } from '@bitdrift/react-native';

init('<api key>', sessionStrategy: SessionStrategy.Activity, {
  enableNetworkInstrumentation: true
});

Enabling this via the Objective-C API is not yet supported if initialization is done via the native API - please reach out if there is interest in this feature.

Android

To enable automatic OkHttp instrumentation on Android, add the io.bitdrift.capture-plugin plugin in the app build.gradle file:

plugins {
    id 'io.bitdrift.capture-plugin' version '<version>'
}

To find the version to use, use the same version of the Capture SDK that is being used in the React Native project. Check the build.gradle file in the node_modules/@bitdrift/react-native/android directory for the version of the Capture SDK being used.

For manual Gradle setup, enable plugin instrumentation:

bitdrift {
    instrumentation {
        automaticOkHttpInstrumentation = true
        // Optional. Defaults to PROXY when omitted.
        // okHttpInstrumentationType = OVERWRITE
    }
}

In addition to this the plugin repository needs to be added to the pluginManagement block in the settings.gradle file:

pluginManagement {
    repositories {
        mavenCentral()
        gradlePluginPortal()
        maven {
            url 'https://dl.bitdrift.io/sdk/android-maven'
            content {
                includeGroupByRegex "io\\.bitdrift.*"
            }
        }
    }
}

When using Expo to generate the project, this can be achieved by setting the networkInstrumentation option to true in the app.json file:

{
  "expo": {
    "plugins": [
        [
          '@bitdrift/react-native',
          {
            networkInstrumentation: true,
          },
        ],
    ]
  }
}

When using the Expo plugin with networkInstrumentation: true, the Android Gradle plugin and bitdrift { instrumentation { ... } } block are generated automatically.

WebView Integration

WebView instrumentation captures telemetry from react-native-webview webviews like page views, network requests, navigation events, Web Vitals, long tasks, console logs, user interactions and errors. Call init(...) before any WebView is mounted.

iOS

Enable automatic instrumentation of every WebView by passing UNSTABLE_enableWebViewInstrumentation: true to init:

import { init, SessionStrategy } from '@bitdrift/react-native';

init('<api key>', SessionStrategy.Activity, {
  UNSTABLE_enableWebViewInstrumentation: true,
});

Android

UNSTABLE_webViewInstrumentation is intended for Android app builds.

For Expo-generated Android apps, enable build-time WebView bytecode instrumentation with:

{
  "expo": {
    "plugins": [
      [
        "@bitdrift/react-native",
        {
          "UNSTABLE_webViewInstrumentation": true
        }
      ]
    ]
  }
}

Notes:

  • UNSTABLE_webViewInstrumentation only affects Android app builds. On iOS, use UNSTABLE_enableWebViewInstrumentation in init.
  • It is not automatically applied to vanilla React Native Android builds outside the Expo config plugin flow.
  • For non-Expo Android apps, apply the Gradle plugin and bitdrift { instrumentation { automaticWebViewInstrumentation = true } } manually.

The Android plugin mode can be configured with okHttpInstrumentationType:

{
  "expo": {
    "plugins": [
      [
        "@bitdrift/react-native",
        {
          "networkInstrumentation": true,
          "okHttpInstrumentationType": "OVERWRITE"
        }
      ]
    ]
  }
}

okHttpInstrumentationType is Android-only and has no effect on iOS.

  • PROXY (default): preserves existing EventListener.Factory behavior in OkHttp clients.
  • OVERWRITE: replaces the listener factory and can avoid duplicate network spans in some app setups.

If you recently upgraded and started seeing duplicate spans on Android, set okHttpInstrumentationType to OVERWRITE.

版本与发布记录

@bitdrift/react-native 共发布 82 个版本,首次发布于 2024/04/02;过去 12 个月发布了 47 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.15.0latest2026/10/2316 天前
0.14.12026/09/291 个月前
0.14.02026/09/231 个月前
0.13.22026/09/111 个月前
0.13.12026/09/042 个月前
0.13.02026/09/042 个月前

其他发布通道:rc → 0.5.1-rc.1。

关于 @bitdrift/react-native 的常见问题

@bitdrift/react-native 是什么?

bitdrift integration for React Native

如何安装 @bitdrift/react-native?

在项目目录运行 npm install @bitdrift/react-native,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(*)、react-native(*)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@bitdrift/react-native 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@bitdrift/react-native 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@bitdrift/react-native 可以商用吗?

@bitdrift/react-native 使用 SEE LICENSE IN LICENSE 许可。许可条款写在包内的独立文件中,请阅读该文件确认可否商用。以上为概括,不构成法律意见,请以许可原文为准。

@bitdrift/react-native 的下载量有多少?

根据 npm 官方下载统计,@bitdrift/react-native 在 2026/10/08 – 2026/11/06 这 30 天内被下载 59,911 次,日均约 1,997 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bitdrift/react-native 还在维护吗?

最新版本 0.15.0 发布于 2026/10/23(16 天前);至今共发布 82 个版本,其中过去 12 个月发布了 47 个;首次发布于 2024/04/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。