React Native
@zharp/react-native sends a React Native or Expo app's JavaScript errors, native crashes and logs with the session and device they came from, and traces its screens and requests into your API.
This SDK is new, and its API may still change before 1.0. Requires React Native 0.74 or later (0.75 for native iOS crashes), or Expo SDK 51 or later.
Install
The quickest way, in the app's folder — it works for Expo and bare React Native:
npm init zharp@latest
It signs you in, creates or picks the app in Zharp, installs the SDK, starts it, wires release builds for readable stack traces, and puts the upload key where git ignores it. It shows every change before making it.
By hand
npm install @zharp/react-native # Expo: npx expo install @zharp/react-native cd ios && pod install # bare React Native
Initialize
First thing in index.js, before the app registers:
// index.js — before AppRegistry.registerComponent
import { AppRegistry } from 'react-native';
import { Zharp } from '@zharp/react-native';
import App from './App';
import { name as appName } from './app.json';
Zharp.init({
key: 'zpk_…',
service: 'shop-app',
environment: 'production',
tracingOrigins: ['api.example.com'], // your API: its requests carry traceparent
});
AppRegistry.registerComponent(appName, () => App);With Expo Router, start it at the top of the root layout, which also records each screen:
// app/_layout.tsx (Expo Router)
import { Stack, useNavigationContainerRef } from 'expo-router';
import { Zharp, useZharpNavigation } from '@zharp/react-native';
Zharp.init({ key: 'zpk_…', service: 'shop-app' });
export default function RootLayout() {
useZharpNavigation(useNavigationContainerRef()); // each screen, with its requests
return <Stack />;
}The key is safe to ship in the app: it can only send. Turn the SDK off in development with enabled: !__DEV__.
Logs
Zharp.log.info('Checkout opened', { items: 3 }); // trace, debug, info, warn, error, fatalEach log carries the session, user, device, current screen and trace. By default only what you send with Zharp.log goes to Zharp. Set logs: true to also send console output (captureConsole picks the methods).
Logs only
If you only want logs, turn tracing off. Logs, errors, and the user and session they belong to are still sent; no spans are recorded and no trace headers are added to outgoing requests.
Zharp.init({
key: "zpk_…",
service: "shop-app",
tracing: false,
});The logs show on the Logs page under the service name, and on the app's Logs tab with the user and session of each line. The key comes from an app — see Get a key. To add tracing later, remove the option; nothing else changes.
Errors
- Uncaught JavaScript errors, through React Native's global handler — the red box in development and React Native's own crash in release still happen as before.
- A fatal JavaScript error is written to the device before the app closes and sent on the next launch, once. React Native's native copy of it is not reported again.
- Unhandled promise rejections (Hermes).
- Native crashes, ANRs and hangs, from Zharp's Android and iOS SDKs, which the package starts underneath. JavaScript errors and native crashes share one session and user.
Report one you caught yourself:
try {
await checkout(cart);
} catch (error) {
Zharp.captureError(error, { orderId: order.id }); // handled
}React render errors
ZharpErrorBoundary reports what a render throws, with the components that were rendering, and shows a fallback. On React 19, Zharp.reactErrorHandler() does the same for the root's error options.
import { ZharpErrorBoundary } from '@zharp/react-native';
<ZharpErrorBoundary fallback={<Text>Something went wrong.</Text>}>
<App />
</ZharpErrorBoundary>Readable stack traces
Release builds run Hermes bytecode, so a stack names index.android.bundle or main.jsbundle, not your files. With the build's source map uploaded, Zharp shows — and groups — those errors by your original functions, files and lines, with the code, and no repository needed. npm init zharp@latest sets all of this up.
1. Metro
withZharpConfig gives every release bundle a debug ID that its errors carry and its source map is filed under:
// metro.config.js (React Native)
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const { withZharpConfig } = require('@zharp/react-native/metro');
module.exports = withZharpConfig(mergeConfig(getDefaultConfig(__dirname), {}));// metro.config.js (Expo)
const { getDefaultConfig } = require('expo/metro-config');
const { withZharpConfig } = require('@zharp/react-native/metro');
module.exports = withZharpConfig(getDefaultConfig(__dirname));2. The builds upload the source map
Expo: add the config plugin. On npx expo prebuild and EAS Build it wires both native projects as below.
// app.json
{
"expo": {
"plugins": ["@zharp/react-native"]
}
}Bare React Native: one line in android/app/build.gradle, and two in the Xcode build phase that bundles the JavaScript:
// android/app/build.gradle, after apply plugin: "com.facebook.react"
apply from: new File(["node", "--print", "require.resolve('@zharp/react-native/package.json')"].execute(null, rootDir).text.trim(), "../zharp.gradle")# Build Phases → "Bundle React Native code and images": first line, after set -e
export SOURCEMAP_FILE="${SOURCEMAP_FILE:-$DERIVED_FILE_DIR/main.jsbundle.map}"
# …React Native's own lines, unchanged…
# last line
/bin/bash "$PODS_ROOT/../../node_modules/@zharp/react-native/ios/zharp-upload.sh"3. The upload key
The upload needs ZHARP_AUTH_TOKEN, a workspace key with the artifacts:write scope (see The upload key), and ZHARP_APP, the app's ID. Never put the upload key in the app. Without it, the build says so and carries on.
- CI: set both as environment variables.
- Bare React Native, on your machine: in files git ignores —
# android/local.properties (git ignores it) zharp.authToken=zh_… zharp.appId=123 # ios/.xcode.env.local (git ignores it) export ZHARP_AUTH_TOKEN=zh_… export ZHARP_APP=123
- Expo, on your machine: in
.env.local. EAS Build: as secrets —
eas env:create --name ZHARP_AUTH_TOKEN --value zh_… --visibility secret eas env:create --name ZHARP_APP --value 123
EAS Update
An update ships its own bundles. Upload their source maps after publishing:
eas update # or: npx expo export --source-maps npx zharp react-native upload --dir dist --app 123
Source maps include your source code, so errors show it without a linked repository. That code is stored with the build's artifacts in your workspace.
Tracing
Screens
Pass your navigation container's ref to useZharpNavigation (React Navigation, or Expo Router's useNavigationContainerRef()). Each screen becomes a screen <name> span lasting until its requests are done, and everything recorded meanwhile carries the screen name. Zharp.trackNavigation(ref) does the same outside a component.
import { createNavigationContainerRef, NavigationContainer } from '@react-navigation/native';
import { useZharpNavigation } from '@zharp/react-native';
const navigationRef = createNavigationContainerRef();
export default function App() {
useZharpNavigation(navigationRef);
return <NavigationContainer ref={navigationRef}>{/* … */}</NavigationContainer>;
}
// Or by hand:
Zharp.trackScreen('Checkout');Requests
Every fetch and XMLHttpRequest is a span, with its request and response headers (secret ones such as authorization and cookies recorded as [Filtered]). Requests to hosts in tracingOrigins carry traceparent and baggage, so your API's spans join the same trace; other hosts get no extra headers.
Spans of your own
const invoice = await Zharp.startSpan('render invoice', async () => render(order));
Zharp.setTag('plan', 'pro'); // on everything afterRequest and response bodies
Off by default. Turn it on to see what a request sent and what came back, shown under the request in the trace: every request except Zharp's own, or only those to tracingOrigins when you set them; urls narrows that.
Zharp.init({
key: 'zpk_…',
captureBodies: 'errors', // failed requests only; 'all' for every request
});
// more control:
captureBodies: { mode: 'all', maxSize: 4096, redactKeys: ['dateOfBirth'], urls: ['api.shop.com'] }- Failed requests only (status 400 and above, or no response) by default; every request with the "all" mode.
- Text (JSON, forms, XML, plain text) is kept up to 32 KB, up to 128 KB with the size option.
- Every field name is kept. A file in an upload shows as
[file photo.png · image/png · 240 KB], an inline image as[image/png · 24 KB], a body that isn't text as[binary · application/pdf · 1.2 MB]or[event stream]. File contents are never sent. - Your app reads and sends exactly what it did before.
Values under keys that look secret — password, token, secret, apiKey, authorization, cookie, card, cvv, ssn and similar — are replaced with [Filtered] in the app, before anything is sent. The field stays; only its value is hidden, and under a secret object such as card each value inside is hidden and its keys kept. Anything else, such as names and email addresses, is sent as it is: add those keys to redactKeys.
Whether or not bodies are on, secret-looking values in URL query strings (?token=, key, sig, password …) are recorded as [Filtered].
User context
Zharp.setUser({ id: user.id, email: user.email }); // once someone signs in
Zharp.clearUser(); // on sign-out: also starts a new session- A session ID on everything, the same for JavaScript errors and native crashes; a new session after 30 minutes in the background or idle, and on
clearUser(). - OS and version, device model and manufacturer, the React Native version and whether Hermes runs.
Options
| Option | Default | Notes |
|---|---|---|
key | — | Required. |
service | react-native-app | service.name |
environment | none | deployment.environment.name |
release | none | e.g. shop-app@2.3.0+41 |
tracingOrigins | [] | Hosts (api.example.com), origins or RegExps |
captureHeaders | true | Request and response headers on request spans; { redact: ['x-tenant'] } filters more names |
captureBodies | off | 'errors' or 'all'. See Request and response bodies. |
logs | false | true sends console output |
captureConsole | all methods | With logs: which console methods |
tracing | true | false is logs only |
sampleRate | 1 | Share of traces kept; errors and logs are always sent |
ignoreUrls | [] | URLs never traced |
enabled | true | e.g. !__DEV__ |
sessionTimeoutMinutes | 30 | In the background or idle |
debug | false | The native SDK prints what it does (Logcat, Xcode console) |
Telemetry is batched every 5 seconds or 100 records, and sent when the app goes to the background. Zharp.flush() sends now. The SDK never throws into your app.
Expo Go
Expo Go can't load the package's native code, so there it reports JavaScript errors, logs and requests only. A development build or a release build has everything.
Troubleshooting
Nothing arrives
On the app's setup page (Applications → the app → settings → Setup instructions), the verify step shows the first event as soon as it lands, and Send a test event checks the key on its own. If the test event arrives but your app's don't, the SDK isn't starting or isn't reaching Zharp:
- Is
initcalled, and before the code you expect to see? Without a key, the SDK starts nothing and says so once. - Does the service name match? With an app key everything goes to that app whatever it says; with a workspace key,
servicedecides the app — see Keys. - Data is sent in batches every few seconds. A process that exits straight away should call
flushfirst. - Logs and errors arrive but no traces? Check that tracing isn't turned off — see Logs only.
- On an Android emulator,
localhostis the emulator itself; a local Zharp is at10.0.2.2. - Windows: React Native's Android build can hit the 260-character path limit (
Filename longer than 260 characters). Build from a short folder, or turn on Windows long paths. - Expo SDK 58 iOS release builds need an Xcode that Expo supports; if
ExpoModulesJSIfails to compile, it does so without Zharp too. - Errors still show
index.android.bundle: check thatmetro.config.jsuseswithZharpConfigand that the release build's output has noZharp:note saying the source map wasn't uploaded.
401 or 403
Ingest answers 401 when the key is missing, mistyped, revoked or rolled, and 403 when the request comes from an origin or IP address the key doesn't allow. Neither is retried: the SDK warns once and drops what was refused, and it never throws into your code. Copy the key again from the app's settings.