> ## Documentation Index
> Fetch the complete documentation index at: https://docs.crispstats.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> CrispStats is a hosted, privacy-first analytics product. It has no self-hosted edition, no session replay, no heatmaps, no A/B testing and no data import except a site's history from a Plausible export (Settings, Import and export). Websites use the script. iOS, Android, React Native and Flutter use the mobile SDKs in the install guides. Those SDKs are source files, not a published package, and they do not read an advertising id.
> The script global is crispstats(...), site keys start with cs_pk_ and secret API keys start with cs_sk_. The script is served from https://in.crispstats.com/d.js and the REST API lives at https://crispstats.com/api/v1.
> The script tag is the main install; the npm package @crispstats/tracker does the same from code, never alongside the tag. Integrations copy the script tag, the queue stub, crispstats.d.ts and proxy code from these docs or from Settings, Tracking code in the dashboard. A first-party proxy forwards one path of the site to https://in.crispstats.com/p/ and forwards only content-type, user-agent, accept-language, referer, origin, if-none-match and x-forwarded-for, never cookies.

# Install CrispStats in a React Native app

> Add the CrispStats TypeScript file to a React Native or Expo app and send screen views, campaigns, custom events, identify and revenue with the site's public key.

The React Native client is one TypeScript file with no imports. It runs on Hermes and in Expo. It keeps a random install id in the storage you pass in, queues events while the network is down, and sends them to `https://in.crispstats.com/e`. It does not read the advertising identifier.

## Get the file

From the folder where you keep app code, for example `src/analytics`:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -O https://crispstats.com/sdk/react-native/crispstats.ts
```

Then import it by its relative path, such as `./crispstats`. To update, download it again.

## Count screens

Create one client in its own module and import it wherever you need it.

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// src/analytics/index.ts
import { AppState, Dimensions, Platform } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { CrispStats, asyncStorage, bindAppState, deviceFor } from "./crispstats";

const { width, height } = Dimensions.get("window");

export const analytics = new CrispStats({
  site: "cs_pk_xxxxxxxx",
  platform: Platform.OS === "ios" ? "ios" : "android",
  appId: "com.acme.app",
  appVersion: "1.4.0",
  appBuild: "42",
  osVersion: String(Platform.Version),
  device: deviceFor({
    isPad: Platform.OS === "ios" && Platform.isPad,
    shortestSideDp: Math.min(width, height),
  }),
  sdk: "react-native",
  storage: asyncStorage(AsyncStorage),
});

bindAppState(analytics, AppState);
```

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
analytics.screen("Home");
analytics.track("signup", { plan: "pro" });
analytics.identify("user_42", { plan: "pro" });
analytics.revenue(4900, "USD");
```

Replace `cs_pk_xxxxxxxx` with the site's public key from **Settings**, **Tracking code**, and `com.acme.app` with the bundle id or application id. `platform` is the device, `ios` or `android`, not the name of the SDK. `revenue` takes minor units: `4900` with `USD` is \$49.00. A negative amount is ignored.

`storage` must have `get` and `set`. AsyncStorage names them `getItem` and `setItem`, so wrap it with `asyncStorage` as above. `memoryStorage()` keeps everything in memory, which suits tests.

`Platform.Version` on Android is the API level, not the Android release. Pass the release string when you have it.

Call `screen` on each navigation. The client sends the previous screen's visible time first. `bindAppState` calls `leave` when the app leaves the foreground and `resume` when it comes back, so time on screen stops while the app is in the background. After 30 minutes or more away, the collector has started a new session, so `resume` counts the current screen again and its time starts from zero.

A screen name is one to eight segments of letters, numbers, spaces, `.`, `_` and `-`, separated by `/`, each up to 80 characters and 200 in all. `Settings/Account` is stored as the page `/Settings/Account`. A name outside these rules, such as `../secret` or `Search?q=x`, is ignored and nothing is sent.

## Tablets

`device` is `phone` unless you pass `tablet`. `deviceFor` returns `tablet` on an iPad (`Platform.isPad`) or when the shorter side of the window is at least 600 dp, which is the usual Android tablet line. The sample above uses it.

## Campaigns from a deep link

Pass the link's campaign tags with the screen it opens. `campaignFromUrl` reads them from the URL.

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { Linking } from "react-native";
import { campaignFromUrl } from "./crispstats";

function openLink(url: string | null) {
  if (!url) return;
  analytics.screen("Promo", undefined, {
    campaign: campaignFromUrl(url),
    referrer: "https://partner.example/post",
  });
}

Linking.getInitialURL().then(openLink);
Linking.addEventListener("url", ({ url }) => openLink(url));
```

`campaignFromUrl("acme://promo?utm_source=newsletter&utm_medium=email")` returns `{ utm_medium: "email", utm_source: "newsletter" }`. The third argument of `screen` takes:

* `campaign`: query parameters such as `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`, `ref` and ad click ids such as `gclid`. A key is lower-cased and must be 1 to 32 letters, numbers or `_`. A value is trimmed and must be 1 to 200 characters. Other pairs are left out, and at most 10 are kept.
* `referrer`: the URL that sent the user, up to 2,000 characters.

Both apply to that one screen view. `utm_source` and `utm_medium` set the channel, the same way they do on a web page. Later events on the screen do not repeat them.

## Opt out

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
analytics.optOut();
analytics.optIn();
```

`optOut` drops anything still queued, sends nothing, and is remembered in storage across launches. `optIn` starts sending again. If the app opted out before the first launch finished, `optIn` creates the install id then.

## Errors

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
analytics.recordError("Checkout failed", "CheckoutScreen");
```

The message is grouped on the Errors page. The source is the screen or file name, and it is optional.

## When the network is down

Events wait in storage, up to the newest 100. The client tries again when it starts, when the app returns to the foreground, after each new event, and on a timer that waits 1 second, then 2, then 4, up to 60. A request that takes longer than 10 seconds is tried again later. `await analytics.flush()` sends the queue now.

No call throws, and no call waits for the network. Time on screen is measured from when you call `screen`, `leave` and `resume`, not from when the request finishes.

If an option can never produce a valid event, such as a site key that does not start with `cs_pk_`, an `appId` that is not a bundle id, or an empty `appVersion`, the client sends nothing and logs one `console.warn` that names the problem.

## A stronger install id

The install id is 16 random bytes from `crypto.getRandomValues`. Hermes does not always provide it, and then the client falls back to `Math.random`. For a stronger id, install `react-native-get-random-values` and import it once, first thing in the app's entry file:

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import "react-native-get-random-values";
```

In Expo, you can use `expo-crypto` instead:

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import * as Crypto from "expo-crypto";
import { randomInstallId } from "./crispstats";

// Add to the options of new CrispStats(...)
randomId: () => randomInstallId((size) => Crypto.getRandomBytes(size)),
```

The language and time zone come from `Intl` when the device has it, as a tag such as `en-US` and a zone such as `Europe/Berlin`. Pass `locale` and `timezone` to set them yourself.

## What gets stored

The screen is a pageview. The browser breakdown shows **iOS app** or **Android app**, and a tablet shows as **tablet**. The app version, build, OS version and SDK name are properties on the event, and the SDK is `react-native`. The install id itself is not stored. See [mobile apps](https://docs.crispstats.com/install/mobile.md) for the rest of the mapping.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.