tracwell-react-native
v0.3.0
Published
Small, framework-neutral React Native analytics SDK for Tracwell
Maintainers
Readme
Tracwell React Native SDK
Framework-neutral analytics for React Native and Expo applications. The SDK tracks screens, custom events, and optional product identity; batches delivery; and flushes when the app leaves the foreground.
Install
pnpm add tracwell-react-native @react-native-async-storage/async-storageInitialize
import { createAsyncStorage } from "@react-native-async-storage/async-storage";
import { AppState } from "react-native";
import { createTracwell } from "tracwell-react-native";
const analytics = await createTracwell({
appId: "com.example.app",
appState: AppState,
collectionMode: "product",
projectKey: "tw_live_...",
projectOrigin: "https://example.com",
storage: createAsyncStorage("tracwell"),
});appId should be the stable iOS bundle identifier or Android application ID.
It becomes the hostname of the analytics URL, such as
app://com.example.app/Home, so mobile traffic remains separate from website
traffic without inventing a second event model.
projectOrigin is the exact HTTPS origin already registered for the Tracwell
project. The Collector checks it for native requests just as it checks the
browser Origin header for web requests.
Private mode is the default and does not persist identity. Product mode uses
the supplied AsyncStorage-compatible adapter. If product persistence is
enabled without an adapter, the SDK reports STORAGE_UNAVAILABLE and uses
in-memory identity for that app process.
Track screens and events
analytics.screen("Home");
analytics.track("upgrade_started", { plan: "pro" });
analytics.identify("customer_123");
const session = analytics.getSession();getSession() returns the active Product-mode anonymousId, sessionId, and
optional userId. Pass these opaque identifiers through a server-created
checkout and include them in its authenticated revenue event so the purchase
retains the originating mobile session. It returns undefined in Private mode,
without consent, or after shutdown.
Treat these IDs as attribution context, not authorization. Revenue user_id
must come from the authenticated account or verified payment webhook rather
than a client-supplied value.
Identifying a different user on the same installation rotates both anonymous
identity and session before recording the new identity. Call
await analytics.reset() on logout so an anonymous post-logout visit also
starts cleanly.
Call screen() from the navigation library's route-change callback. The SDK
does not depend on React Navigation, Expo Router, or another router, so the same
client works across React Native frameworks. Consecutive duplicate screen
callbacks are ignored.
For React Navigation, pass the current route name from NavigationContainer:
<NavigationContainer
ref={navigationRef}
onReady={() => analytics.screen(navigationRef.getCurrentRoute()?.name ?? "Unknown")}
onStateChange={() => analytics.screen(navigationRef.getCurrentRoute()?.name ?? "Unknown")}
>
{/* application navigators */}
</NavigationContainer>Lifecycle and delivery
- Normal delivery uses React Native's global
fetchand the same bounded/v1/eventscontract as the browser SDK. - Events and batch IDs are created before delivery and remain stable across
retries. Retryable failures back off from 2 s, doubling to at most 5 minutes,
until the oldest event nears the Collector's 24-hour age limit (an explicit
maxRetriesof 0-5 caps attempts). Periodic flushes wait for a scheduled retry. While delivery is failing at most 100 events are held in memory, and the oldest waiting events are dropped. Held events are not persisted across app restarts. - A configured
AppStateadapter flushes when the app becomes inactive or enters the background. React Native does not guarantee that an arbitrary asynchronous request will finish after suspension, so important flows can alsoawait analytics.flush()explicitly. shutdown()removes timers and AppState listeners after a final flush.- Consent can start as
required; collection begins only afteranalytics.setConsent("granted").
The project key and project origin are intentionally public. Native
applications cannot provide a browser's trustworthy origin boundary, but the
Collector still requires an exact configured-origin match before accepting a
contract-valid tracwell-react-native batch. Project status, usage
enforcement, payload validation, and project-level rate limiting remain in
force.
Structure
src/
index.ts Stable async factory and public exports
client.ts Consent, screen state, identity, lifecycle, and public API
config.ts Strict native configuration and shared defaults
identity.ts AsyncStorage-compatible anonymous, session, and user state
events.ts Application URL and contract-compatible event creation
preflight.ts Lightweight event, size, and receipt checks
runtime.ts React Native web-platform globals and UUID generation
transport.ts Batching, receipt validation, and backoff retry
client.test.ts Deterministic identity, lifecycle, and retry coverage
scripts/
build.mjs Minified, self-contained ESM build
smoke.mjs Packed runtime and TypeScript consumer verificationThe published package has no React, router, or native-module dependency.
@tracwell/contracts is used at build time and its required limits are bundled
into the artifact. Storage and AppState are structural adapters supplied by the
application.
Verify
pnpm --filter tracwell-react-native typecheck
pnpm --filter tracwell-react-native test
pnpm --filter tracwell-react-native check:package