
# Expo SDK

`@kerdly/expo` runs the native Kerdly SDKs for iOS and Android inside your Expo or React Native app.
It adds a config plugin, captures deep links on its own, and gives you one TypeScript API for both
platforms.

## Requirements

- Expo SDK 52 or newer (developed against SDK 57), or a bare React Native app with Expo modules.
- A development or production build: `npx expo prebuild`, `npx expo run:ios`, or EAS Build.
  **Expo Go and web don't contain the native code**; there every call does nothing and you get one
  development warning.
- iOS 15 or newer; Android 7.0 (API 24) or newer.

## Before you start

An Expo app that ships to both stores is **two Kerdly apps**, Tallybird iOS and Tallybird Android,
each with its own app key. Create both apps in your project (the product form at sign-up does this
when you tick iOS and Android), then open each app's **Settings → SDK**: its app key is already made and shown in the code to paste.

| Kerdly app | Bundle id / package | Key |
|---|---|---|
| Tallybird iOS | `com.example.tallybird` | `pk_live_ios…` |
| Tallybird Android | `com.example.tallybird` | `pk_live_and…` |

App keys are public; they ship inside your app. Never put a server key (`sk_…`) in the app; the SDK
refuses it.

## Install

```sh
npx expo install @kerdly/expo
```

Add the config plugin to `app.json` (or `app.config.ts`):

```json
{
  "expo": {
    "plugins": [
      [
        "@kerdly/expo",
        {
          "metaAppId": "1234567890123456",
          "userTrackingPermission": "Lets us measure which of our ads brought you to Tallybird."
        }
      ]
    ]
  }
}
```

Then rebuild the native projects: `npx expo prebuild` (or your next EAS build).

| Plugin option | Platform | What it does |
|---|---|---|
| `metaAppId` | Android | Your Facebook app id. Turns on the Meta Install Referrer read, which matches installs from Meta ads. |
| `userTrackingPermission` | iOS | Sets `NSUserTrackingUsageDescription`, the App Tracking Transparency prompt text. Needed for `requestTrackingAuthorization()`. |
| `skanEndpoint` | iOS | Sets `NSAdvertisingAttributionReportEndpoint`, so copies of SKAdNetwork postbacks reach Kerdly. Use the address on the iOS app's **Settings → SKAdNetwork** page. |

The plugin only sets the keys it is given and never removes an Info.plist key, so values you set in
`ios.infoPlist` survive. Running it twice changes nothing.

The Android side adds the `INTERNET` and `com.google.android.gms.permission.AD_ID` permissions and
`<queries>` entries for the Facebook, Instagram and Facebook Lite apps (Meta Install Referrer). An
app that must not read the advertising id blocks `AD_ID` with Expo's `android.blockedPermissions`
and passes `collectAdvertisingId: false`.

## Configure

Call `configure` once, as early as possible: at module scope of your root file (`app/_layout.tsx`
with Expo Router, `App.tsx` otherwise), not inside a component. Pick the key by platform:

```ts
// app/_layout.tsx
import { Platform } from 'react-native';
import { Kerdly } from '@kerdly/expo';

Kerdly.configure({
  key: Platform.select({
    ios: process.env.EXPO_PUBLIC_KERDLY_IOS_KEY!,         // pk_live_… of Tallybird iOS
    android: process.env.EXPO_PUBLIC_KERDLY_ANDROID_KEY!, // pk_live_… of Tallybird Android
  })!,
});
```

A second `configure` is ignored. Calls made before `configure` are held and run after it.

| Option | Default | |
|---|---|---|
| `key` | required | The app's public key: `pk_live_…`, or `pk_test_…` for test builds. |
| `endpoint` | `https://app.kerdly.com/api` | Change it only if Kerdly support asks you to. |
| `environment` | `'auto'` | `'production'`, `'sandbox'` or `'development'`. `'auto'` lets the native SDK decide from the build. |
| `collectAdvertisingId` | `true` | Read the IDFA (only when the user allowed tracking) or the GAID. |
| `skanWriter` | `false` | iOS: let Kerdly write SKAdNetwork conversion values. Only one SDK in an app should write them. |
| `metaAppId` | the plugin's | Android: overrides the plugin's `metaAppId`. |
| `logLevel` | `'warn'` | `'none'`, `'error'`, `'warn'`, `'info'` or `'debug'`. |
| `autoDeepLinks` | `true` | Forward React Native `Linking` URLs to the SDK. |

No function throws and no promise rejects. Invalid input is dropped with a development warning.

## Users

After sign-in, set your own user id; it is attached to every later event. Clear it on sign-out.

```ts
Kerdly.setUserId(user.id);
Kerdly.setUserId(null);
```

## Standard events

What the app sends and what comes from the stores is laid out step by step in
[Track the whole funnel](https://kerdly.com/docs/sdks/funnel.md#setup-1-an-app-that-sells-through-the-stores). The
full setup, with store notifications, deferred deep links and postbacks, is in
[App with App Store and Google Play billing](https://kerdly.com/docs/guides/store-app.md); if you also sell on the web,
see [App with web payments](https://kerdly.com/docs/guides/app-web-payments.md).

Send these when they happen. Every field is optional, and a malformed field is dropped with a
warning, never the whole event.

```ts
Kerdly.trackRegistration({ method: 'apple' });

Kerdly.trackStartTrial({ productId: 'tallybird_pro_weekly', value: 0, currency: 'USD', transactionId });

Kerdly.trackSubscribe({
  productId: 'tallybird_pro_annual',
  value: 39.99,
  currency: 'USD',
  transactionId,
  properties: { paywall: 'onboarding_v2' },
});

Kerdly.trackPurchase({ productId: 'tallybird_streak_freeze', value: 1.99, currency: 'USD', quantity: 1, transactionId });
```

- `value` is what the user paid, in `currency` (three letters, ISO 4217). Without a valid currency
  the value is dropped.
- `productId` and `transactionId` are cut to 128 characters, `method` to 64.
- `properties` adds custom props. A key that is one of the event's typed fields (`value`,
  `product_id`, …) is dropped: set it through the typed field.

## Custom events

```ts
Kerdly.track('habit_created', { category: 'fitness', reminders: true });
```

Names and prop keys match `^[a-z][a-z0-9_]{0,39}$`. At most 25 props; values are strings (cut to
256 characters), finite numbers or booleans.

## Link purchases to the install

Renewals and refunds come from the stores. To credit them to the right campaign, link each store
purchase to the install.

1. Tell the SDK the account token your purchases carry: on iOS the StoreKit `appAccountToken` (a
   UUID), on Android the Play `obfuscatedAccountId`.
2. After each completed purchase, pass the transaction to `notifyPurchase`.

```ts
import { Platform } from 'react-native';
import { Kerdly } from '@kerdly/expo';

Kerdly.setAppAccountToken(accountToken);

// in your purchase callback
if (Platform.OS === 'ios') {
  Kerdly.notifyPurchase({
    originalTransactionId: tx.originalTransactionId,
    transactionId: tx.transactionId,
    productId: tx.productId,
    appAccountToken: tx.appAccountToken,
  });
} else {
  Kerdly.notifyPurchase({
    purchaseToken: tx.purchaseToken,
    orderId: tx.orderId,
    products: [tx.productId],
  });
}
```

Each transaction is linked once; calling it again is harmless. On iOS, `Kerdly.notifyPurchase()`
with no argument (after a restore, say) links the current entitlements.

### With Superwall

```tsx
import { useEffect } from 'react';
import { Platform } from 'react-native';
import { useSuperwallEvents, useUser } from 'expo-superwall';
import { Kerdly } from '@kerdly/expo';

export function KerdlySuperwallBridge() {
  const { user } = useUser();
  const alias = user?.aliasId; // "$SuperwallAlias:3F2504E0-4F89-41D3-9A0C-0305E82C3301"

  useEffect(() => {
    if (!alias) return;
    const aliasUuid = alias.replace(/^\$SuperwallAlias:/, '');
    Kerdly.setAppAccountToken(Platform.OS === 'ios' ? aliasUuid : alias);
    Kerdly.setPartnerIds({ superwall_alias: alias });
  }, [alias]);

  useSuperwallEvents({
    onSuperwallEvent: ({ event }) => {
      if (event.event !== 'transactionComplete') return;
      const tx = event.transaction;
      if (Platform.OS === 'ios') {
        Kerdly.notifyPurchase({
          originalTransactionId: tx?.originalTransactionIdentifier,
          transactionId: tx?.storeTransactionId,
          productId: event.product.productIdentifier,
          appAccountToken: tx?.appAccountToken,
        });
      } else if (tx?.purchaseToken) {
        Kerdly.notifyPurchase({
          purchaseToken: tx.purchaseToken,
          orderId: tx.storeTransactionId,
          products: [event.product.productIdentifier],
        });
      }
    },
  });

  return null;
}
```

Render it inside `<SuperwallProvider>`.

## Deep links

With `autoDeepLinks: true` (the default), the SDK receives the URL that opened the app and every
later link from React Native `Linking`. `expo-dev-client` launcher URLs are skipped. Don't also call
`handleUrl` for those URLs.

For a link that never reaches `Linking`, such as a deferred link from another SDK:

```ts
const link = await Kerdly.handleUrl(url);
// { url, cpp, ppid, clickId, visitId, campaignIds }, each null when absent
```

## Attribution

Read which network and campaign brought the install. It is `null` until Kerdly decides, and
`state` says whether the answer is `provisional` or `final`.

```tsx
import { useEffect, useState } from 'react';
import { Kerdly, type KerdlyAttribution } from '@kerdly/expo';

export function useAttribution() {
  const [attribution, setAttribution] = useState<KerdlyAttribution | null>(null);
  useEffect(() => {
    const sub = Kerdly.addAttributionListener(setAttribution);
    return () => sub.remove();
  }, []);
  return attribution; // attribution?.network: 'meta' | 'tiktok' | 'apple_ads' | 'organic' | …
}
```

## Consent and App Tracking Transparency

```ts
Kerdly.setConsent({ analytics: true, ads: false });
```

- `analytics: false` keeps only the SDK's own events (installs and opens).
- `ads: false` stops reading the IDFA or GAID.
- An omitted flag keeps its value.

The SDK never shows the iOS tracking prompt on its own. To ask (after setting
`userTrackingPermission` in the plugin):

```ts
const status = await Kerdly.requestTrackingAuthorization();
// 'authorized' | 'denied' | 'restricted' | 'not_determined'; 'not_applicable' on Android
```

## Recording sends to ad networks

If the app also reports conversions to Meta or TikTok through their SDKs, record each send with the
same event id the network gets, so Kerdly can show both sides:

```ts
Kerdly.recordNetworkSend({ network: 'meta', event: 'StartTrial', eventId, value: 0, currency: 'USD' });
```

## API

| Call | Does |
|---|---|
| `await Kerdly.configure(options)` | Starts the native SDK. |
| `Kerdly.setUserId(id \| null)` | Your user id, attached to every later event. |
| `Kerdly.track(name, props?)` | A custom event. |
| `Kerdly.trackRegistration({ method?, properties? })` | Standard event `registration`. |
| `Kerdly.trackStartTrial({ productId?, value?, currency?, transactionId?, properties? })` | Standard event `start_trial`. |
| `Kerdly.trackSubscribe({ productId?, value?, currency?, transactionId?, properties? })` | Standard event `subscribe`. |
| `Kerdly.trackPurchase({ productId?, value?, currency?, quantity?, transactionId?, properties? })` | Standard event `purchase`. |
| `Kerdly.setConsent({ analytics?, ads? })` | Consent flags. |
| `await Kerdly.handleUrl(url)` | Records a deep link and returns what it carried, or `null`. |
| `Kerdly.setAppAccountToken(token \| null)` | iOS `appAccountToken`; Android `obfuscatedAccountId`. |
| `Kerdly.setPartnerIds(ids)` | Ids other SDKs own; an empty value removes a key. |
| `Kerdly.notifyPurchase(purchase?)` | Links a store purchase to the install. |
| `Kerdly.recordNetworkSend(send)` | A conversion the app sent to an ad network itself. |
| `await Kerdly.getAttribution()` | The install's attribution, or `null` until known. |
| `Kerdly.addAttributionListener(fn)` | Calls `fn` now (when known) and on every change. Returns `{ remove() }`. |
| `await Kerdly.requestTrackingAuthorization()` | iOS ATT prompt; `'not_applicable'` on Android. |
| `await Kerdly.flush()` | Sends the queue now. |
| `await Kerdly.getInstallId()` | The install id, or `null` before `configure`. |

## Data and privacy

The native SDKs do the collecting. For your App Store and Google Play privacy answers, see
[iOS: Data and privacy](https://kerdly.com/docs/sdks/ios.md#data-and-privacy)
and [Android: Data and privacy](https://kerdly.com/docs/sdks/android.md#data-and-privacy).
The SDK never collects names, email addresses, phone numbers, location or clipboard contents.

## Check it's working

1. Set `logLevel: 'debug'` and run a development build on a device or simulator.
2. Look for `[Kerdly]` lines in the Xcode console or logcat: the SDK logs what it sends and any error Kerdly answers with.
3. In the dashboard, the app's **Onboarding** page shows the SDK step with the time of the last
   event. Check both Tallybird iOS and Tallybird Android.

## Troubleshooting

- Nothing happens in Expo Go: expected. Use a development build.
- Kerdly answers `bundle_mismatch`: the key belongs to the other platform's Kerdly app, or the bundle
  id doesn't match the app's. Check the `Platform.select`.
- Kerdly answers `bad_key` or `key_revoked`: the key was mistyped or revoked; create a new one under Settings → SDK.
- Questions or problems: [open an issue](https://github.com/Kerdly/kerdly-sdk/issues) or contact
  Kerdly support. Never post your keys.

---

Source: https://kerdly.com/docs/sdks/expo. Index of all docs: https://kerdly.com/llms.txt
