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

# Set up event tracking

> Install the event SDK, verify that Sagepilot receives samples, and publish an event mapping for your website or React Native app.

Use the Sagepilot event SDK to collect activity from your website or React Native app and publish rules that turn it into named events. On the web, you can start a customer journey after a visitor verifies their email. The React Native installation SDK collects anonymous activity, including after an app user signs in.

You need settings write access in Sagepilot, access to deploy your website or rebuild your app, and an analytics permission setting you can read and listen to. Use a test installation to verify the setup first.

## Create an installation

1. Open **Settings → SDK Events** in your Sagepilot workspace.
2. Select **New installation**, enter a name, and choose a platform.
   * **Web**. In **Allowed website origins**, enter one origin per line, such as `https://shop.example.com`. Include the scheme and any non-default port. Add the origin you will use for testing and use HTTPS in production.
   * **Android** or **iOS**. Set **App identifier** to the Android application ID or iOS bundle identifier. Create one installation per platform.
3. Turn on **Installation enabled** and **Event collection permitted**, then click **Save installation**.
4. Copy the **Installation key**, which has the format `workspace_id:installation_id`. You can include this key in your website or app code.

## Choose your API host

Set `apiHost` to the origin where you sign in to your Sagepilot workspace. The SDK gets its event upload URL when it starts a session.

| Workspace region | `apiHost` |
| - | - |
| India | `https://app.sagepilot.ai` |
| Europe | `https://eu.sagepilot.ai` |

## Install the SDK

Install the latest published Event SDK for your platform. The commands use `@latest` so you get the current release when you install or upgrade.

Replace each example key with the installation key for that platform. The examples use the India API host. For a European workspace, replace it with `https://eu.sagepilot.ai`.

> [tab] Web with npm
>
> Install the web events add-on.
>
> ```bash theme={null}
> npm install @sagepilot-ai/web-events-addon@latest
> ```
>
> Save this as `sagepilot-events.ts` and import it once from your browser entry point. If your framework renders on the server, load the module in a browser-only startup hook such as a React effect.
>
> ```ts theme={null}
> import { createSagepilotWebEvents } from "@sagepilot-ai/web-events-addon";
>
> export const events = createSagepilotWebEvents({
>   key: "WORKSPACE_ID:INSTALLATION_ID",
>   apiHost: "https://app.sagepilot.ai",
>   collectionEnabled: false,
> });
> const ready = events.start();
> void ready.catch(console.error);
>
> /** Applies the site's analytics permission after SDK startup. */
> export async function setSagepilotAnalyticsAllowed(allowed: boolean) {
>   await ready;
>   await events.setCollectionEnabled(allowed);
> }
>
> const testConsent = document.querySelector<HTMLInputElement>("#sagepilot-test-analytics");
> testConsent?.addEventListener("change", () => {
>   void setSagepilotAnalyticsAllowed(testConsent.checked).catch(console.error);
> });
> ```
>
> Import `setSagepilotAnalyticsAllowed` where your site reads analytics permission. Call it with the current decision when your consent manager is ready and again whenever the decision changes.

> [tab] Web with a script
>
> Download the latest standalone browser bundle and upload it to your site's assets. Repeat these steps when you upgrade the hosted bundle.
>
> ```bash theme={null}
> sagepilot_tarball=$(npm pack @sagepilot-ai/web-events-addon@latest --silent) &&
> tar -xOzf "$sagepilot_tarball" package/dist/sagepilot-web-events.global.js > sagepilot-web-events.global.js
> ```
>
> Add this to your page template. Replace `src` with the versioned URL of the file you uploaded.
>
> ```html theme={null}
> <script defer src="/assets/sagepilot/SDK_VERSION/sagepilot-web-events.global.js"></script>
> <script>
>   document.addEventListener("DOMContentLoaded", () => {
>     const events = window.SagepilotWebEvents.createSagepilotWebEvents({
>       key: "WORKSPACE_ID:INSTALLATION_ID",
>       apiHost: "https://app.sagepilot.ai",
>       collectionEnabled: false,
>     });
>     const ready = events.start();
>     ready.catch(console.error);
>
>     window.setSagepilotAnalyticsAllowed = async (allowed) => {
>       await ready;
>       await events.setCollectionEnabled(allowed);
>     };
>
>     const testConsent = document.getElementById("sagepilot-test-analytics");
>     testConsent?.addEventListener("change", () => {
>       window.setSagepilotAnalyticsAllowed(testConsent.checked).catch(console.error);
>     });
>   }, { once: true });
> </script>
> ```
>
> After the page setup runs, call `window.setSagepilotAnalyticsAllowed(allowed)` with the current decision from your consent manager and again whenever it changes.

> [tab] React Native
>
> Use React 18 or later and React Native 0.81.5 or later. The add-on supports Android API 24 and later and iOS 15.1 and later. The example uses AsyncStorage and a random-value helper to create and reuse an anonymous ID.
>
> ```bash theme={null}
> npm install @sagepilot-ai/react-native-events-addon@latest \
>   @react-native-async-storage/async-storage@2.2.0 react-native-get-random-values@2.0.0
> ```
>
> Save this as `sagepilot-events.native.js` and import `./sagepilot-events` once at native app startup. Replace the key and app identifier for each platform you ship.
>
> ```js theme={null}
> import "react-native-get-random-values";
> import AsyncStorage from "@react-native-async-storage/async-storage";
> import { Platform } from "react-native";
> import { createSagepilotInstallationEvents } from "@sagepilot-ai/react-native-events-addon";
>
> const installation = Platform.OS === "ios"
>   ? { key: "WORKSPACE_ID:IOS_INSTALLATION_ID", appId: "com.example.ios" }
>   : { key: "WORKSPACE_ID:ANDROID_INSTALLATION_ID", appId: "com.example.android" };
>
> export const eventsReady = (async () => {
>   const storageKey = `sagepilot:events:anonymous:${installation.key}`;
>   let anonymousId = await AsyncStorage.getItem(storageKey);
>   if (!anonymousId) {
>     const bytes = new Uint8Array(16);
>     globalThis.crypto.getRandomValues(bytes);
>     anonymousId = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
>     await AsyncStorage.setItem(storageKey, anonymousId);
>   }
>
>   const events = createSagepilotInstallationEvents({
>     ...installation,
>     apiHost: "https://app.sagepilot.ai",
>     anonymousId,
>     collectionEnabled: false,
>   });
>   await events.start();
>   return events;
> })();
> void eventsReady.catch(console.error);
>
> /** Applies the app's analytics permission after SDK startup. */
> export async function setSagepilotAnalyticsAllowed(allowed) {
>   const events = await eventsReady;
>   await events.setCollectionEnabled(allowed);
> }
> ```
>
> Call `setSagepilotAnalyticsAllowed(allowed)` after loading the app's analytics permission and whenever the user changes it. Keep the random ID in app storage across launches.
>
> Rebuild and run your app after installing the native modules. For bare React Native, run the command for your platform.
>
> ```bash theme={null}
> # Android
> npx react-native run-android
>
> # iOS
> cd ios && pod install && cd ..
> npx react-native run-ios
> ```
>
> For Expo, use a development build with the native modules included.
>
> ```bash theme={null}
> npx expo install expo-dev-client
> npx expo run:android
> # On macOS for iOS, run npx expo run:ios instead.
> ```

Turning off analytics permission stops capture and clears unsent events. If your site or app already knows the user's decision at startup, you can pass it as `collectionEnabled` when you create the SDK. Use `false` while the decision is unknown.

## Verify the install

Open the registered test site or a fresh native build and grant analytics permission. If you need a web test control, add this to your test page before the startup code runs. Both web examples connect it to the SDK.

```html theme={null}
<label>
  <input id="sagepilot-test-analytics" type="checkbox" autocomplete="off" />
  Allow analytics for this test
</label>
```

For a React Native test control, import `Button` from `react-native` and `setSagepilotAnalyticsAllowed` from your startup module. Add this to a test screen.

```jsx theme={null}
<Button
  title="Allow analytics for this test"
  onPress={() => void setSagepilotAnalyticsAllowed(true).catch(console.error)}
/>
```

For production, use the site's or app's analytics permission setting.

* **Web.** In your browser's **Network** tab, check that the request ending in `/sdk/sessions` succeeds. For the npm install, `events.diagnostics().enabled` should be `true` after you grant permission.
* **React Native.** After you grant permission, check that `(await (await eventsReady).diagnostics()).enabled` is `true` in your test build.

## Discover and publish events

1. In **Settings → SDK Events**, select your installation.
2. Under **Event mappings**, set **Discovery hours** and click **Start discovery**.
3. With analytics permission enabled, perform the actions you want to track during the discovery window. For an add-to-cart mapping, complete a cart addition and browse a product without adding it. Collect a matching sample for each rule you want to publish and an action that should match none of those rules.
4. Click **Refresh** and check that the sample count increases. Click **Generate AI proposal** while the samples are available.
5. Review the proposed names and leave the rules you want enabled. If you change any rules or toggle them, click **Save rules**. Click **Validate rules**, then **Publish mapping** when validation passes.
6. Check that **Event mappings** shows **Serving version** followed by the version you published.

If your site or app changes, click **Remap** to collect new samples and review a new version. The current mapping stays active until you publish another one.

## Verify a web event in a customer journey

Use a test workspace and an email address you control. You need permission to create and publish journeys.

1. [Publish a website popup](#publish-a-website-popup) with **Verify email with a code** selected.
2. In **Engage → Journeys**, click **Create journey** and name it. Choose your published event from the **Sdk** source as the trigger. Under **Steps**, add a one-minute **Wait** step. Review the setup and click **Publish journey**.
3. Open the test storefront on a page that matches the popup's display rules. Grant analytics permission, submit your test email, and enter the verification code.
4. In the same browser, perform the mapped action again. Open the verified test customer's profile in Sagepilot. Check that the event appears in the timeline and that the customer entered the test journey.

Use the discovery sample count and serving version to verify a React Native installation. Its events remain anonymous and cannot start a customer journey.

## Optional website settings

### Publish a website popup

1. In **Settings → SDK Events**, select your web installation. Under **Website popup**, click **Edit popup**.
2. Under **Content & form**, choose the contact fields. For a customer journey, set **Identity verification** to **Verify email with a code**. The built-in form records marketing opt-in on submission. Make that clear in your popup copy.
3. Use **Design** to adjust the popup's appearance and preview it on desktop and mobile.
4. Open **Display rules**, turn on **Enable popup**, and choose where and when the popup should appear.
5. Click **Save popup draft**, then **Publish popup**. Test on a page that matches the display rules.

### Remember returning browsers with a cookie

The standard install uses browser storage. To use a first-party visitor cookie, proxy `POST /sagepilot/visitor/WORKSPACE_ID/INSTALLATION_ID` on the storefront to `POST /platform-api/v1/sdk/visitors/WORKSPACE_ID/INSTALLATION_ID` on your workspace's [API host](#choose-your-api-host).

Forward the original `Origin`, `Sec-Fetch-Site`, JSON body, and `sagepilot_visitor` cookie. Relay the response, including `Set-Cookie` and `Cache-Control`, to the browser. Keep other storefront cookies and credentials on the storefront.

In your web installation, turn on **First-party visitor cookie** and click **Save installation**. Sagepilot uses it for browsers that allow analytics to recover their visitor ID and popup completion state.

## Troubleshoot a missing event

* **SDK startup returns 404**. Check the [API host](#choose-your-api-host) in your snippet and reload your site or app.
* **Discovery has no samples**. Check that the installation and event collection are enabled, analytics permission is granted, and the web origin or app identifier matches the registration. Repeat the actions before the discovery window closes and click **Refresh**.
* **The discovery window closed without usable samples**. For a first test, create a new test installation and replace its key before starting discovery again. For a remap on a serving installation, contact [Sagepilot Support](mailto:support@sagepilot.ai) with the installation name and draft version so you can keep the current mapping serving.
* **An expected event is missing**. Check that its rule is enabled and the mapping version is serving. Repeat the action and confirm it completed. A successful cart change is evidence for an add-to-cart event. A button click may only record click intent.
* **A web customer did not enter the journey**. Check that the journey is published with the matching trigger and that the customer completed email verification in the same browser before performing the action.
* **The native module is unavailable**. Install the iOS pods if applicable and rebuild the native app. On Expo, open the development build.


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