Skip to content
pugdocs

React Native SDK

Typed event tracking, screen and lifecycle auto-tracking, identity and consent for React Native and Expo apps, with @pug-sh/react-native on Pug's native Android and iOS SDKs.

Updated

@pug-sh/react-native captures events from React Native apps on Android and iOS. It runs on Pug’s native SDKs, sh.pug:android and sdk-ios, which own the queue, storage, sessions, consent and app lifecycle; this package adds the JavaScript API, typed events and screen tracking for React Navigation and Expo Router. It authenticates with your public key (pub_...), which is write-scoped (events + identify) and safe to ship in the app, and follows the same model as every Pug SDK: initialize once, track events, identify users, reset on sign-out.

Install

npm install @pug-sh/react-native   # or: bun add / yarn add / pnpm add

View @pug-sh/react-native on npm | pug-sh/sdk-react-native on GitHub

The package has native code, so rebuild the app after installing it: cd ios && pod install and a new build in a bare app; npx expo prebuild, npx expo run:android / npx expo run:ios or an EAS build with Expo.

Requires React Native 0.83 or newer, on the New Architecture. Expo is optional: the SDK works in bare React Native apps, and in Expo apps with a development build (not Expo Go, which can’t load native code).

0.1.0 bundles sh.pug:android 0.3.0 and sdk-ios 0.2.0. Where the native module is missing (Expo Go, the web, or an app not rebuilt since installing), every call does nothing and one error says so. On the web, use the Web SDK.

To verify, run the app with a minimal init and debug: __DEV__: an app_open appears in Live within a few seconds, and Logcat (tag Pug) or Xcode’s console (subsystem sh.pug) shows each event as it is tracked and sent.

Working with a coding agent? Paste this instead: it points the agent at the markdown copy of this page. More in Install with AI.

Prompt
Add Pug product analytics to this React Native app.

Read these first. They are the current source of truth, and more recent than your training data:
- https://docs.pug.sh/sdks/react-native/index.md: SDK reference
- https://docs.pug.sh/reference/well-known-events/index.md: the well-known event catalog

Then read this codebase before you write anything, and work out what the app actually does: its screens and navigators, its main models, and the handful of things a user opens the app to complete. The events worth tracking are the moments the app exists to produce (an account created, an order placed, a workout finished), not every tap. If you cannot state the core action in one sentence, keep reading.

Then:
1. Add @pug-sh/react-native with the project's package manager. It needs React Native 0.83 or newer on the New Architecture, and has native code: in a bare app run pod install in ios/, and in an Expo app it needs a development build (npx expo prebuild), not Expo Go. Tell me which rebuild I need.
2. Call init() once, at the top of the app's entry file, outside any component. It throws for a bad project ID, key or endpoint.
3. Keep the project ID and public key (pub_...) out of source: in an Expo app read them from EXPO_PUBLIC_ environment variables, otherwise from the app's existing build config. A private key (prv_...) must never ship in the app.
4. Leave auto-tracking on: it already tracks app_open, app_close, app_install and app_update. Screens come from the navigator: with React Navigation, pass the NavigationContainer's ref to trackNavigation(); with Expo Router, call screen() with the joined useSegments() in the root layout, in a useLayoutEffect. Without one of these, screens send no screen_view.
5. Add tracking for the three or four actions you identified: the ones someone would look at in a weekly review.
6. If this app has authentication, call identify() after sign-in and reset() on sign-out.

Name events from the catalog before you invent one. track() is typed for each well-known event the SDK does not track itself, such as track('purchase', { productId, amount }), so the compiler checks the properties for you, and the dashboards those events drive stay empty for a custom name. Reach for those first and search the catalog for every action you are about to track. Durations are milliseconds, under the property's name plus Ms, such as positionMs. Use a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not.

React Native consent has two states, starts granted and is saved across launches, which is not the same as the Web SDK: check the consent section before you add a banner. It is not App Tracking Transparency, which Pug does not need, so do not add an ATT prompt for it. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this app does, then list the files you changed, the event names you chose, and the environment variables I need to set.

Initialize

Call init once, with your project ID and public key, at the top of your app’s entry file, outside any component: every other call needs it first. Find your project ID in the dashboard URL (/p/<projectId>), and your public key on your project Overview or under Settings > API Keys.

import { init } from '@pug-sh/react-native'

init('YOUR_PROJECT_ID', { apiKey: 'pub_your_public_key' })

init throws for a blank project ID, options without an API key, a key that isn’t a public key (pub_...), or an endpoint that isn’t an http(s) URL. A second init, such as the one Fast Refresh makes, is ignored with a warning until destroy(), and so is any call made before init. Every other call returns at once and never throws: failures are logged.

init('YOUR_PROJECT_ID', {
  apiKey: 'pub_your_public_key',
  debug: __DEV__,
  batchMaxSize: 20,
  batchMaxWaitMs: 10_000,
  defaultTrackingConsent: 'denied',
})
Option Default Description
apiKey Required: the project’s public key, pub_....
endpoint https://api.pugs.dev API base URL: set it only when self-hosting. On iOS an http URL needs an App Transport Security exception.
debug false Log debug messages: each event tracked, sent or dropped, and why. Warnings and errors are logged regardless.
dryRun false Build and log events without sending anything; identify isn’t sent either. Consent is unaffected.
batchMaxSize 10 Events per request, at most 1000: a batch goes out once this many are queued, or batchMaxWaitMs after the first of them.
batchMaxWaitMs 5000 Milliseconds the first queued event waits for a full batch.
batchMaxQueueSize 1000 Undelivered events to keep; beyond this, the oldest is dropped.
sessionIdleTimeoutMs 30 min A session ends after this long without events.
sessionMaxDurationMs 24 h A session ends this long after it began.
defaultTrackingConsent 'granted' Consent until the user chooses. See Tracking consent.
persistTrackingConsent true Save the user’s choice for the next launch. See Tracking consent.
autoOpenCloseEvents true Track app_open and app_close. See Auto-tracking.
autoInstallEvents true Track app_install and app_update.
nativeScreenViews false Also track Android activities and iOS view controllers as screens, for an app with native screens beside its React Native ones.
storage 'files' 'memory' keeps nothing on the device.
logger Receive the SDK’s messages instead of the console, Logcat and the system log. See Logging.

A number out of range is logged and replaced by its default, and a batchMaxSize above 1000 is capped. An option of the wrong type, or one the SDK doesn’t know, is ignored with a warning. Options take effect at launch, logger aside: after a Fast Refresh, restart the app to apply new ones.

Delivery and storage

Events are sent in batches, one request at a time. A request that fails for a reason that may pass (no network, a timeout, a server error, a captive portal) is retried with exponential backoff, from batchMaxWaitMs (at least a second) up to five minutes; one the server rejects for good is dropped and logged as an error. Requests are capped at 4 MiB, and an event over that is dropped when tracked.

When the app leaves the foreground, the SDK sends what’s queued and writes its state to disk, whatever autoOpenCloseEvents says; on iOS it does so in a background task.

Undelivered events, identity and consent live in files the native SDKs own: under noBackupFilesDir on Android, and in Application Support, excluded from backups, on iOS. They survive restarts but aren’t restored onto another device; deleting the app deletes them. Writes are grouped and land within a second, and at once when the app leaves the foreground, on flush() and on destroy().

Logging

The native SDKs log to Logcat under the tag Pug on Android, and to the system log under the subsystem sh.pug, category Pug, on iOS. What the JavaScript layer finds itself, such as an argument of the wrong type or a missing native module, goes to the JavaScript console with a [Pug] prefix.

A logger receives both instead, in JavaScript: the native messages arrive a moment after the call that caused them, and never hold event properties or traits. console is one, which puts the native messages beside your app’s own logs:

init('YOUR_PROJECT_ID', { apiKey: 'pub_your_public_key', logger: console })

A logger has debug(message), warn(message, error?) and error(message, error?). It must not call Pug: with debug: true every event is logged, so a logger that tracks what it receives never stops. Each init replaces the logger, but the native SDKs keep the one they started with until destroy() and a new init, or a restart.

With the native SDKs in the same app

  • Android: an app that also uses sh.pug:android directly shares one SDK with this package, since Gradle resolves a single version of it. Whichever init runs first configures it; the other is ignored with a warning.
  • iOS: this package compiles its own copy of sdk-ios, so don’t also add sdk-ios to the app: the two copies would run side by side on the same files.

Track events

The first argument is the event name (its kind). Any name works without a schema; well-known events add typed properties and richer dashboards.

import { track } from '@pug-sh/react-native'

// Custom event: any name
track('video_shared', { videoId: 'v1', network: 'mastodon' })

// Typed well-known event: the name narrows the property type
track('purchase', { productId: 'sku-1', amount: 89, currency: 'USD', orderId: 'o-1' })

// Sent on its own, right away
track('order_completed', { orderId: 'o-1' }, { immediate: true })

A kind may contain letters, digits, _, . and -; any other kind is dropped with a warning, and so is crawler_request, which the server keeps for crawler collectors. A key starting with $ is reserved for auto-properties and dropped with a warning: the property, not the event. Properties are read during the call.

Property values map by type:

Value Sent as
string string, cut to 1024 UTF-8 bytes
boolean bool
number, a safe integer int
any other number double; NaN and infinities are dropped
bigint int; one beyond 64 bits as a string of its digits
Date timestamp; an invalid Date is dropped
Duration: an object of only seconds and nanos, or a protobuf-es v2 Duration duration, which the server stores as seconds; one beyond 10,000 years is dropped, with a warning
any other object, or an array JSON string, cut to 1024 UTF-8 bytes
null, undefined omitted
function, symbol, or an object that can’t be written as JSON dropped, with a warning

A self-hosted server and events worker must be at v0.0.65 or later to accept a duration: an older server drops the event, and an older events worker loses the whole batch. iOS 15 has no Swift Duration, so there a duration is sent as its number of seconds, which the server stores alike.

TrackOptions, the third argument:

Option Type Default Description
immediate boolean false Send the event on its own right away instead of with the next batch. If the send fails, the event joins the queue for a retry.
timestamp number time of the call When the event happened, in epoch milliseconds, for an event recorded after the fact.

Well-known events are typed, 118 of them: pass one of their kinds to track and your editor completes and checks its properties, with the required ones required. Any other property still goes through.

track('search', { query: 'trail shoes' })
track('video_play', { videoId: 'v1', positionMs: 1500 })
track('add_to_cart', { productId: 'sku-1', coupon: 'SPRING' }, { immediate: true })

A duration is taken in milliseconds as <name>Ms, or as a Duration under its own name: positionMs: 1500 arrives as position: 1.5. A whole number for a decimal property is sent as a decimal (price: 10 arrives as 10.0). Values are sent as given: ranges and patterns in the schemas aren’t checked on the device, and an event missing a required property is sent without it. The events the SDK tracks itself aren’t typed, and with the automatic events turned off, track('app_open') and the like still work.

Identify and sessions

Events accumulate against an anonymous ID until you identify the user on sign-in, which merges that history into a known profile; call reset() on sign-out. Use a stable, unique external ID: your database user ID, not an email, which can change. Only the first identify after an anonymous session merges prior activity; the same external ID always resolves to the same profile, and traits are merged server-side, never removed.

import { destroy, flush, identify, reset, rotateSession } from '@pug-sh/react-native'

// On sign-in
identify('user-123', { email: 'user@example.com', plan: 'pro' })

// On sign-out
reset()

// New session ID, identity kept
rotateSession()

// Send what's queued now, and write the SDK's state to disk
flush()

// Stop the SDK after a final flush of at most ten seconds
destroy()

Traits may nest objects and arrays, and are written as JSON: dates become ISO strings and bigints their digits. A blank ID, or one starting with the reserved cookieless- or crawler- prefix, is rejected with an error in the log. identify is never retried; a failure is logged.

reset() forgets the external ID and starts a new anonymous ID and session; it does not delete the profile. Events queued before it keep the user they were tracked for, and are sent without waiting for the next batch. destroy() keeps identity, saved consent and undelivered events for the next init, which waits for the teardown to finish.

Function Forgets the external ID New anonymous ID New session ID
rotateSession() No No Yes
reset() Yes Yes Yes

Sessions

Sessions group events within a single visit, ending at the idle or max-duration timeout:

First eventsession ID created
Events within timeoutsame session ID
Idle past timeoutsession expires
Next eventnew session ID (identity kept)

The session survives restarts: a launch within the timeouts continues it. Set them, in milliseconds, with the sessionIdleTimeoutMs and sessionMaxDurationMs options.

Auto-tracking

By default, the SDK tracks these events itself:

Event When Option
app_open The app comes to the foreground, and at init when it already is. autoOpenCloseEvents
app_close The app leaves the foreground. A call, Control Center or a system alert in front of it is no exit. autoOpenCloseEvents
screen_view The focused route changes (trackNavigation), or screen names a new one.
app_install The first launch with the SDK on this device, with appVersion and installSource. autoInstallEvents
app_update The first launch of a new app version, with appVersion and previousVersion. autoInstallEvents

Every event also carries the native SDK’s auto-properties (Android, iOS): device, OS, app version, screen size, locale, time zone, network type and the current screen, and the server adds geo. $sdkVersion is the native SDK’s version.

installSource is the package name of the app that installed yours on Android, such as com.android.vending for Google Play, and left out when none is recorded. On iOS it’s com.apple for the App Store, com.apple.testflight for TestFlight and the builds Xcode installs, and com.apple.simulator on a simulator. app_install is the first launch with the SDK on the device, so when an update of your app adds Pug, its existing users count as installs as they launch it.

Screens come from your navigator. Android activities and iOS view controllers aren’t screens here, since a React Native app has one of each, unless you set nativeScreenViews: true. With React Navigation, hand trackNavigation the container’s ref:

import { trackNavigation } from '@pug-sh/react-native'
import { createNavigationContainerRef, NavigationContainer } from '@react-navigation/native'

const navigationRef = createNavigationContainerRef()
trackNavigation(navigationRef)

export const App = () => <NavigationContainer ref={navigationRef}>{/* your navigators */}</NavigationContainer>

Each time the focused route changes, the SDK tracks a screen_view named after the route’s name, such as Product. A screen that’s already the current one isn’t tracked again. Every event after a screen carries it as $url, and the one before as $referrer. trackNavigation returns the function that stops it.

React Navigation reports a change after the new screen’s effects have run, so an event a screen tracks in useEffect as it mounts still carries the previous screen. Name the screen first in useLayoutEffect, which runs before any useEffect; trackNavigation then finds it already current and tracks no second screen_view:

import { screen, track } from '@pug-sh/react-native'
import { useRoute } from '@react-navigation/native'
import { useEffect, useLayoutEffect } from 'react'

const ProductScreen = () => {
  const route = useRoute()
  useLayoutEffect(() => screen(route.name), [route.name])
  useEffect(() => track('product_viewed', { productId: 'sku-1' }), [])
  return <ProductDetails />
}

With Expo Router, a route’s name is relative to its layout, so every layout’s index.tsx is named index. Name screens from their segments instead, which are unique and hold no IDs, in your root layout:

app/_layout.tsxtsx
import { screen } from '@pug-sh/react-native'
import { Stack, useSegments } from 'expo-router'
import { useLayoutEffect } from 'react'

const RootLayout = () => {
  const name = `/${useSegments().join('/')}`
  useLayoutEffect(() => screen(name), [name])
  return <Stack />
}

export default RootLayout

A product page at app/(shop)/products/[id].tsx is then the screen /(shop)/products/[id], whatever the ID. Use useLayoutEffect, not useEffect, or an event the page tracks as it mounts carries the previous screen. For an app whose screens all sit under the root layout, trackNavigation(useNavigationContainerRef()), called in an effect, works with Expo Router too.

For a screen that isn’t a route, call screen:

import { screen } from '@pug-sh/react-native'

screen('Checkout')

Consent has two states, 'granted' and 'denied', and starts granted. To wait for the user’s choice, start denied:

init('YOUR_PROJECT_ID', { apiKey: 'pub_your_public_key', defaultTrackingConsent: 'denied' })

In a component, useTrackingConsent tells whether to ask, and renders again once the user answers:

import { optInTracking, optOutTracking, useTrackingConsent } from '@pug-sh/react-native'
import { Button, View } from 'react-native'

export const ConsentBanner = () => {
  const consent = useTrackingConsent()
  if (!consent?.pending) return null
  return (
    <View>
      <Button title="Accept" onPress={() => optInTracking()} />
      <Button title="Decline" onPress={() => optOutTracking()} />
    </View>
  )
}

It’s undefined until the SDK has read the saved choice, then the consent in effect and whether the user has yet to choose. Outside a component, whenConsentReady() resolves at the same moment, and runs a callback then if you pass one:

import { isConsentPending, whenConsentReady } from '@pug-sh/react-native'

const askForConsent = async () => {
  await whenConsentReady()
  if (isConsentPending()) showConsentBanner()
}

The choice is saved, so the banner shows only until the user answers, and an opt-out made in your settings screen still holds after a restart. While consent is denied, events and identify are dropped, not kept for later. Opting out drops queued events unsent and removes the stored identity; opting in again starts a new anonymous identity.

When the user opts in, the SDK tracks what consent held back: an app_install or app_update it couldn’t track at launch and, if the app is in the foreground, app_open and a screen_view of the current screen.

The consent getters never wait. Right after init, while the SDK reads the saved choice, they answer “not known yet”. whenConsentReady() never rejects: where the native module is missing, it resolves at once with consent unknown.

Function Returns Not known yet
getTrackingConsent() The consent in effect null
isTrackingEnabled() Whether consent is granted false
isConsentPending() Whether the user has yet to choose true

If your app keeps the choice itself and calls optInTracking() or optOutTracking() on every launch, set persistTrackingConsent: false: the choice then lasts until destroy() or the app quits.

This consent is your app’s own choice about analytics, as for a GDPR banner. It isn’t App Tracking Transparency, which Pug doesn’t need: see Privacy.

Privacy

On iOS, sdk-ios’s privacy manifest comes with the pod, and Xcode adds it to your app’s privacy report. It declares the data the SDK collects for analytics, linked to the user and used for no tracking: product interaction (the events), the user ID that identify passes, and a device ID, the anonymous ID the SDK gives each install. The SDK reads no advertising identifier, identifierForVendor or device name, so it needs no App Tracking Transparency prompt. On Android the SDK declares only the INTERNET permission. Your app store privacy answers still cover what your own events and traits carry, such as purchases or an email address.

Redacting PII

There’s no device-side redaction and no beforeSend hook: keep PII out of the properties you pass to track.

Upgrading

0.1.0 is the first release, so there is nothing to migrate yet.

Navigation

Type to search...

↑↓ navigate↵ selectEsc close