πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance NoData component and React Native SDK documentation
Bill Yang628e7593afa7
diff --git a/client/src/app/[site]/components/Header/NoData.tsx b/client/src/app/[site]/components/Header/NoData.tsxindex fc78d9d23..f1a2e203f 100644--- a/client/src/app/[site]/components/Header/NoData.tsx+++ b/client/src/app/[site]/components/Header/NoData.tsx@@ -130,6 +130,7 @@ export function NoData() {const visibleGuides = showAllPlatforms ? PLATFORM_GUIDES : PLATFORM_GUIDES.slice(0, VISIBLE_PLATFORM_COUNT);const hiddenCount = PLATFORM_GUIDES.length - VISIBLE_PLATFORM_COUNT;+ const isMobileSite = siteMetadata?.type === "mobile";const siteId = siteMetadata?.id ?? siteMetadata?.siteId;const scriptUrl = `${globalThis.location.origin}/api/script.js`;@@ -139,6 +140,21 @@ export function NoData() {const aiPrompt = `Install Rybbit analytics on this website.\n\nAdd this script tag to the <head> of every page, using the root layout or base template if there is one:\n\n<script src="${scriptUrl}" data-site-id="${siteId}" defer></script>\n`;+ const rnInstallSnippet = "npm install @rybbit/react-native @react-native-async-storage/async-storage";++ const rnInitSnippet = `import AsyncStorage from "@react-native-async-storage/async-storage";+import rybbit from "@rybbit/react-native";++await rybbit.init({+ analyticsHost: "${globalThis.location.origin}/api",+ siteId: "${siteId}",+ appIdentifier: "${siteMetadata?.domain || "com.example.app"}",+ storage: AsyncStorage,+ initialScreenName: "Home",+});`;++ const rnAiPrompt = `Install Rybbit analytics in this React Native app.\n\n1. Install the SDK:\n\nnpm install @rybbit/react-native @react-native-async-storage/async-storage\n\n2. Initialize it once in the app entry point:\n\n${rnInitSnippet}\n\n3. If the app uses React Navigation, track screens automatically:\n\nconst navigationTracker = rybbit.createNavigationTracker();\n\n<NavigationContainer\n ref={navigationRef}\n onReady={() => navigationTracker.onReady(navigationRef)}\n onStateChange={() => navigationTracker.onStateChange(navigationRef)}\n>\n\nDocs: https://rybbit.com/docs/sdks/react-native\n`;+return (<section className="mt-4 rounded-lg border border-neutral-100 bg-white p-4 dark:border-neutral-850 dark:bg-neutral-900"><div className="flex flex-col gap-3">@@ -149,93 +165,121 @@ export function NoData() {<span className="relative inline-flex h-3 w-3 rounded-full bg-green-500"></span></span><h2 className="break-words text-base font-semibold tracking-tight text-neutral-900 dark:text-neutral-50">- {t("Waiting for the first pageview from {name}", { name: siteMetadata?.name ?? "" })}+ {isMobileSite+ ? t("Waiting for the first screen view from {name}", { name: siteMetadata?.name ?? "" })+ : t("Waiting for the first pageview from {name}", { name: siteMetadata?.name ?? "" })}</h2></div><p className="text-sm text-neutral-600 dark:text-neutral-400 md:pl-6">- {t("Install the snippet below, then open your site. This page updates on its own once data arrives.")}+ {isMobileSite+ ? t("Install the SDK below, then launch your app. This page updates on its own once data arrives.")+ : t("Install the snippet below, then open your site. This page updates on its own once data arrives.")}</p></div><div className="flex flex-col gap-2">- <Tabs defaultValue="html">+ <Tabs defaultValue={isMobileSite ? "sdk" : "html"}><TabsList>- <TabsTrigger value="html">HTML</TabsTrigger>+ {isMobileSite ? (+ <TabsTrigger value="sdk">React Native</TabsTrigger>+ ) : (+ <TabsTrigger value="html">HTML</TabsTrigger>+ )}<TabsTrigger value="ai">{t("AI agent")}</TabsTrigger></TabsList>- <TabsContent value="html" className="flex flex-col gap-2">- <p className="text-xs text-neutral-600 dark:text-neutral-400">- {t("Paste this into the {headTag} of your website:", { headTag: "<head>" })}- </p>- <CodeSnippet language="HTML" code={htmlSnippet} className="text-xs" />- <div>- <button- type="button"- onClick={() => setShowJsFallback(!showJsFallback)}- aria-expanded={showJsFallback}- className={`inline-flex items-center gap-1 rounded-md text-xs text-neutral-600 transition-colors hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-neutral-50 ${FOCUS_RING}`}- >- <ChevronRight- className={`h-3.5 w-3.5 motion-safe:transition-transform ${showJsFallback ? "rotate-90" : ""}`}- />- {t("If the snippet doesn't work, try JavaScript injection")}- </button>- {showJsFallback && (- <div className="mt-2 flex flex-col gap-2">- <p className="text-xs text-neutral-600 dark:text-neutral-400">- {t("Run this in any JavaScript that loads on every page:")}- </p>- <CodeSnippet language="javascript" code={jsSnippet} className="text-xs" />- </div>- )}- </div>- </TabsContent>+ {isMobileSite && (+ <TabsContent value="sdk" className="flex flex-col gap-2">+ <p className="text-xs text-neutral-600 dark:text-neutral-400">{t("Install the SDK package:")}</p>+ <CodeSnippet language="bash" code={rnInstallSnippet} className="text-xs" />+ <p className="text-xs text-neutral-600 dark:text-neutral-400">+ {t("Initialize it once in your app entry point:")}+ </p>+ <CodeSnippet language="TypeScript" code={rnInitSnippet} className="text-xs" />+ </TabsContent>+ )}+ {!isMobileSite && (+ <TabsContent value="html" className="flex flex-col gap-2">+ <p className="text-xs text-neutral-600 dark:text-neutral-400">+ {t("Paste this into the {headTag} of your website:", { headTag: "<head>" })}+ </p>+ <CodeSnippet language="HTML" code={htmlSnippet} className="text-xs" />+ <div>+ <button+ type="button"+ onClick={() => setShowJsFallback(!showJsFallback)}+ aria-expanded={showJsFallback}+ className={`inline-flex items-center gap-1 rounded-md text-xs text-neutral-600 transition-colors hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-neutral-50 ${FOCUS_RING}`}+ >+ <ChevronRight+ className={`h-3.5 w-3.5 motion-safe:transition-transform ${showJsFallback ? "rotate-90" : ""}`}+ />+ {t("If the snippet doesn't work, try JavaScript injection")}+ </button>+ {showJsFallback && (+ <div className="mt-2 flex flex-col gap-2">+ <p className="text-xs text-neutral-600 dark:text-neutral-400">+ {t("Run this in any JavaScript that loads on every page:")}+ </p>+ <CodeSnippet language="javascript" code={jsSnippet} className="text-xs" />+ </div>+ )}+ </div>+ </TabsContent>+ )}<TabsContent value="ai" className="flex flex-col gap-2"><p className="text-xs text-neutral-600 dark:text-neutral-400">{t("Copy this prompt into Claude Code, Cursor, or another coding agent:")}</p>- <CodeSnippet code={aiPrompt} className="text-xs" />+ <CodeSnippet code={isMobileSite ? rnAiPrompt : aiPrompt} className="text-xs" /></TabsContent></Tabs><div className="flex flex-wrap items-center gap-2 text-xs">- <ExternalLink href="https://rybbit.com/docs/script">{t("Installation docs")}</ExternalLink>- <span className="text-neutral-300 dark:text-neutral-600" aria-hidden="true">- Β·- </span>- <ExternalLink href="https://rybbit.com/docs/script-troubleshooting">- {t("Troubleshooting guide")}- </ExternalLink>+ {isMobileSite ? (+ <ExternalLink href="https://rybbit.com/docs/sdks/react-native">{t("React Native SDK docs")}</ExternalLink>+ ) : (+ <>+ <ExternalLink href="https://rybbit.com/docs/script">{t("Installation docs")}</ExternalLink>+ <span className="text-neutral-300 dark:text-neutral-600" aria-hidden="true">+ Β·+ </span>+ <ExternalLink href="https://rybbit.com/docs/script-troubleshooting">+ {t("Troubleshooting guide")}+ </ExternalLink>+ </>+ )}</div></div>- <div className="flex flex-col gap-2 border-t border-neutral-100 pt-3 dark:border-neutral-850">- <h3 className="text-xs font-medium text-neutral-600 dark:text-neutral-400">- {t("Or follow a setup guide for your platform")}- </h3>- <div className="flex flex-wrap items-center gap-1.5">- {visibleGuides.map(guide => (- <a- key={guide.title}- href={guide.href}- target="_blank"- rel="noopener noreferrer"- className={`group inline-flex h-7 items-center gap-1.5 rounded-md border border-neutral-150 bg-white px-2.5 text-xs font-medium text-neutral-700 transition-colors hover:border-neutral-300 hover:text-neutral-900 dark:border-neutral-800 dark:bg-neutral-850 dark:text-neutral-300 dark:hover:border-neutral-600 dark:hover:text-neutral-50 ${FOCUS_RING}`}+ {!isMobileSite && (+ <div className="flex flex-col gap-2 border-t border-neutral-100 pt-3 dark:border-neutral-850">+ <h3 className="text-xs font-medium text-neutral-600 dark:text-neutral-400">+ {t("Or follow a setup guide for your platform")}+ </h3>+ <div className="flex flex-wrap items-center gap-1.5">+ {visibleGuides.map(guide => (+ <a+ key={guide.title}+ href={guide.href}+ target="_blank"+ rel="noopener noreferrer"+ className={`group inline-flex h-7 items-center gap-1.5 rounded-md border border-neutral-150 bg-white px-2.5 text-xs font-medium text-neutral-700 transition-colors hover:border-neutral-300 hover:text-neutral-900 dark:border-neutral-800 dark:bg-neutral-850 dark:text-neutral-300 dark:hover:border-neutral-600 dark:hover:text-neutral-50 ${FOCUS_RING}`}+ >+ <span className="text-neutral-500 transition-colors group-hover:text-emerald-500 dark:text-neutral-400 dark:group-hover:text-emerald-400">+ {guide.icon}+ </span>+ {guide.title}+ </a>+ ))}+ <button+ type="button"+ onClick={() => setShowAllPlatforms(!showAllPlatforms)}+ className={`inline-flex h-7 items-center rounded-md px-2.5 text-xs font-medium text-neutral-600 transition-colors hover:bg-neutral-100 hover:text-neutral-900 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-neutral-50 ${FOCUS_RING}`}>- <span className="text-neutral-500 transition-colors group-hover:text-emerald-500 dark:text-neutral-400 dark:group-hover:text-emerald-400">- {guide.icon}- </span>- {guide.title}- </a>- ))}- <button- type="button"- onClick={() => setShowAllPlatforms(!showAllPlatforms)}- className={`inline-flex h-7 items-center rounded-md px-2.5 text-xs font-medium text-neutral-600 transition-colors hover:bg-neutral-100 hover:text-neutral-900 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-neutral-50 ${FOCUS_RING}`}- >- {showAllPlatforms ? t("Show fewer") : t("Show {count} more", { count: String(hiddenCount) })}- </button>+ {showAllPlatforms ? t("Show fewer") : t("Show {count} more", { count: String(hiddenCount) })}+ </button>+ </div></div>- </div>+ )}</div></section>);diff --git a/docs/content/docs/(docs)/sdks/react-native.mdx b/docs/content/docs/(docs)/sdks/react-native.mdxindex 72dbdadec..5a08a8ad3 100644--- a/docs/content/docs/(docs)/sdks/react-native.mdx+++ b/docs/content/docs/(docs)/sdks/react-native.mdx@@ -3,14 +3,42 @@ title: React Nativedescription: Official React Native SDK for Rybbit Analytics---+import { Callout } from 'fumadocs-ui/components/callout';++The `@rybbit/react-native` SDK lets you track screens, events, errors, and users in React Native apps. Mobile sites get an App Analytics dashboard mode with mobile-specific labels (e.g. screen views instead of pageviews).++## Creating a Mobile App Site++Before installing the SDK, create a site for your app in the Rybbit dashboard:++1. Click **Add Site** and select the **React Native app** option instead of Website.+2. Enter an app identifier (e.g. `com.example.app`). Letters, numbers, dots, hyphens, and underscores are allowed.+3. Copy the Site ID β you'll pass it to `init()`.+## Installation```bashnpm install @rybbit/react-native @react-native-async-storage/async-storage```+<Callout type="info">+`@react-native-async-storage/async-storage` is recommended but not strictly required. The SDK accepts any storage adapter with `getItem`/`setItem`/`removeItem`. Without one, it falls back to in-memory storage and the anonymous visitor ID will not persist across app launches, so every launch counts as a new visitor.+</Callout>+## Initialization+<Callout type="warning">+`rybbit.init()` **must** be called once before any other tracking methods. Calling other methods first throws an error.+</Callout>++### Syntax++```typescript+async rybbit.init(config: RybbitConfig): Promise<void>;+```++### Example+```tsximport AsyncStorage from "@react-native-async-storage/async-storage";import rybbit from "@rybbit/react-native";@@ -19,31 +47,250 @@ await rybbit.init({analyticsHost: "https://app.rybbit.io/api",siteId: "1",appIdentifier: "com.example.app",+ appVersion: "1.4.2",storage: AsyncStorage,initialScreenName: "Home",});```-## Track Events+### Configuration Options++#### Required Options++| Option | Type | Description |+| :-------------- | :----------------- | :--------------------------------------------------------------------------------- |+| `analyticsHost` | `string` | URL of your Rybbit instance's API (e.g., `https://rybbit.yourdomain.com/api`). |+| `siteId` | `string \| number` | The Site ID for your app obtained from your Rybbit instance. |++#### Optional Options++| Option | Type | Default | Description |+| :---------------------- | :-------------- | :---------- | :------------------------------------------------------------------------------------------------------------------------------------------ |+| `appIdentifier` | `string` | `""` | Identifier for your app (e.g., `com.example.app`). Used as the hostname in tracked data. Falls back to `bundleId`, then the site ID. |+| `bundleId` | `string` | `""` | Alias for `appIdentifier`; used when `appIdentifier` is not set. |+| `appVersion` | `string` | `""` | Your app's version. Appended to the synthetic user agent sent with each event. |+| `tag` | `string` | `""` | A tag added to every event, useful for segmenting data (e.g., by environment or build channel). |+| `storage` | `RybbitStorage` | in-memory | Storage adapter used to persist the anonymous visitor ID and identified user ID. Pass `AsyncStorage` or any compatible object. |+| `storageKeyPrefix` | `string` | `"@rybbit"` | Prefix for storage keys. Keys are namespaced per site: `{prefix}:{siteId}:anonymous-id`. |+| `debug` | `boolean` | `false` | Log SDK warnings (failed requests, config fetch failures) to the console. |+| `autoTrackAppLifecycle` | `boolean` | `true` | Automatically track `app_open` and `app_background` events on `AppState` changes. See [App Lifecycle Events](#app-lifecycle-events). |+| `initialScreenName` | `string` | `""` | If set, a screen view for this name is tracked during `init()` (unless Track Initial Pageview is disabled in your dashboard). |+| `configTimeoutMs` | `number` | `3000` | Timeout in milliseconds for fetching remote tracking config during `init()`. On timeout or failure, the SDK proceeds with defaults. |+| `maxQueueSize` | `number` | `100` | Maximum number of failed events kept in the in-memory retry queue. See [Offline Handling](#offline-handling-and-retries). |+| `fetch` | `typeof fetch` | global | Custom `fetch` implementation. Defaults to the global `fetch`. |++#### Remote Configuration++During `init()`, the SDK fetches your site's tracking settings from the dashboard. Two of them affect the React Native SDK:++| Dashboard Setting | Effect |+| :--------------------- | :---------------------------------------------------------------------------- |+| Track Initial Pageview | When disabled, the `initialScreenName` screen view is not tracked on init. |+| Capture Errors | When disabled, calls to `rybbit.error()` are silently ignored. |++Web-only settings (session replay, Web Vitals, outbound links, autocapture) do not apply to mobile apps.++## Tracking Screens++Screens are the mobile equivalent of pageviews. Each screen view is tracked with the screen name as both the path and title.++### Syntax++```typescript+rybbit.screen(name: string, properties?: TrackProperties, context?: TrackContext): Promise<void>;+```++### Parameters++- **`name`** (`string`, Required): The screen name (e.g., `"Home"`, `"Checkout"`). Used as the pathname (`/Home`) and page title.+- **`properties`** (`object`, Optional): Additional key-value pairs attached to the screen view.+- **`context`** (`object`, Optional): Overrides for the tracked payload. See [Track Context](#track-context).++### Example```tsx-await rybbit.event("signup_started", { plan: "pro" });-await rybbit.identify("user_123", { plan: "pro" });-await rybbit.error(error);+await rybbit.screen("Checkout");++// With properties and an explicit path+await rybbit.screen("Product", { productId: "sku-123" }, { pathname: "/products/sku-123" });+```++You can also track a raw path directly, mirroring the web SDK:++```typescript+rybbit.pageview(path?: string, context?: TrackContext): Promise<void>;```## React Navigation+The SDK ships a navigation tracker that hooks into React Navigation's `NavigationContainer` and automatically tracks a screen view whenever the active route changes. Consecutive events for the same route name are deduplicated.+```tsx+import { NavigationContainer, useNavigationContainerRef } from "@react-navigation/native";+import rybbit from "@rybbit/react-native";+const navigationTracker = rybbit.createNavigationTracker();-<NavigationContainer- ref={navigationRef}- onReady={() => navigationTracker.onReady(navigationRef.current)}- onStateChange={() => navigationTracker.onStateChange(navigationRef.current)}->- {/* screens */}-</NavigationContainer>+function App() {+ const navigationRef = useNavigationContainerRef();++ return (+ <NavigationContainer+ ref={navigationRef}+ onReady={() => navigationTracker.onReady(navigationRef)}+ onStateChange={() => navigationTracker.onStateChange(navigationRef)}+ >+ {/* screens */}+ </NavigationContainer>+ );+}+```++### Options++```typescript+rybbit.createNavigationTracker(options?: NavigationTrackerOptions): NavigationTracker;+```++| Option | Type | Default | Description |+| :------------------ | :---------------------- | :------------------------------- | :--------------------------------------------------------------------------------- |+| `includeRouteParams`| `boolean` | `false` | Include the route's params as a `routeParams` property on the screen view. |+| `getRouteName` | `(route) => string` | `route.name` | Customize how the screen name is derived from the current route. |+| `getPath` | `(route) => string` | `route.path` or `route.name` | Customize the tracked pathname for the current route. |++The returned tracker exposes `onReady`, `onStateChange`, and `trackCurrentRoute` β all take the navigation ref and track the current route if it changed. It works with any navigation library whose ref exposes a `getCurrentRoute()` method.++<Callout type="warning">+Route params can contain sensitive data (IDs, tokens, emails). Only enable `includeRouteParams` if your route params are safe to store in analytics.+</Callout>++## Tracking Custom Events++### Syntax++```typescript+rybbit.event(name: string, properties?: TrackProperties, context?: TrackContext): Promise<void>;+```++### Parameters++- **`name`** (`string`, Required): The name of the event you want to track.+- **`properties`** (`object`, Optional): Additional key-value pairs related to the event.++### Example++```tsx+await rybbit.event("signup_started", { plan: "pro" });++await rybbit.event("purchase_completed", {+ orderId: "order-123",+ total: 49.99,+ currency: "USD",+});+```++## Error Tracking++Capture handled errors with additional context. Error tracking must be enabled in your Rybbit dashboard (Capture Errors) β when disabled, `error()` calls are ignored.++### Syntax++```typescript+rybbit.error(error: Error | unknown, properties?: TrackProperties, context?: TrackContext): Promise<void>;+```++Non-`Error` values are converted to an `Error`. The message is truncated to 500 characters and the stack trace to 2,000.++### Example++```tsx+try {+ await processPayment(order);+} catch (error) {+ await rybbit.error(error, { component: "checkout", orderId: order.id });+ showErrorMessage();+}```-Session replay and Web Vitals are web-only features and are not available for React Native apps.+<Callout type="info">+Unlike the web SDK, the React Native SDK does not automatically capture uncaught exceptions β wrap the code you care about and call `rybbit.error()` yourself.+</Callout>++## User Identification++Associate events with a user ID and optional traits. The ID is persisted through the configured storage adapter and attached to all subsequent events.++```typescript+rybbit.identify(userId: string, traits?: Record<string, unknown>): Promise<void>;+rybbit.setTraits(traits: Record<string, unknown>): Promise<void>;+rybbit.clearUserId(): Promise<void>;+rybbit.getUserId(): string | null;+```++```tsx+// After login+await rybbit.identify("user_123", { plan: "pro", signupDate: "2026-01-15" });++// Update traits later without changing the ID+await rybbit.setTraits({ plan: "enterprise" });++// After logout+await rybbit.clearUserId();+```++<Callout type="info">+`setTraits()` throws if no user has been identified yet β call `identify()` first.+</Callout>++## App Lifecycle Events++With `autoTrackAppLifecycle` enabled (the default), the SDK listens to React Native's `AppState` and tracks:++- **`app_open`** β when the app launches in the foreground or returns to the foreground from the background.+- **`app_background`** β when the app leaves the foreground, with a `state` property (`"background"` or `"inactive"`).++Set `autoTrackAppLifecycle: false` in `init()` to disable these events.++## Offline Handling and Retries++Events that fail to send (e.g., no network) are kept in an in-memory queue, capped at `maxQueueSize` (default 100, oldest dropped first). Queued events are retried when `init()` completes and whenever you call:++```typescript+rybbit.flush(): Promise<void>;+```++<Callout type="warning">+The retry queue is in-memory only β events still queued when the app is killed are lost.+</Callout>++## Track Context++All tracking methods accept an optional `context` object to override what's sent with that event:++| Field | Type | Description |+| :-------------- | :------- | :--------------------------------------------------------------- |+| `appIdentifier` | `string` | Override the hostname for this event. |+| `pathname` | `string` | Override the tracked path. |+| `querystring` | `string` | Query string to attach to the event. |+| `screen` | `string` | Screen name, used as the path/title fallback. |+| `title` | `string` | Override the page title. |+| `referrer` | `string` | Referrer value (empty by default on mobile). |+| `language` | `string` | Override the detected device locale. |+| `userAgent` | `string` | Override the synthetic user agent. |++Device locale, screen dimensions, and a platform-appropriate user agent (including your `appVersion`) are detected automatically.++## Cleanup++Removes the `AppState` lifecycle listener. Call it if you tear down the SDK, e.g. in tests or when unmounting your app root.++```typescript+rybbit.cleanup(): void;+```++## Differences from the Web SDK++- **Session replay** and **Web Vitals** are web-only and not available for React Native apps.+- No automatic outbound link, button click, form, or copy tracking (there is no DOM).+- Uncaught errors are not captured automatically β use `rybbit.error()` in your own error boundaries and catch blocks.+- The anonymous visitor ID is generated by the SDK and persisted via your storage adapter, rather than derived from browser fingerprinting.