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

# Use analytics in the SDK

> Configure @fire-spark/analytics, track events, and control when the queue is sent, who the user is, and what they consented to.

`@fire-spark/analytics` sends each event to Fire Spark and to the destinations you add: GA4, Meta, TikTok, and Masivo. Each destination is its own package. See [Destinations](https://firespark.cloud/docs/guides/analytics/destinations.md) for their options.

## Install

```bash theme={null}
pnpm add @fire-spark/analytics @fire-spark/analytics-ga4
```

## Configure

```typescript theme={null}
import { analytics } from "@fire-spark/analytics";
import { ga4 } from "@fire-spark/analytics-ga4";

await analytics.configure({
  channel_id: "web",
  platform: "web",
  storage: window.localStorage,
  getCustomer: () => session.customer, // { id, is_anonymous } or null
  getScope: () => ({ store_id, brand_id, fulfillment_id }),
  adapters: [ga4({ measurementId: "G-XXXXXXX" })],
  onError: issue => logger.error(issue.message, issue),
  onWarning: issue => logger.warn(issue.message, issue)
});
```

| Option | What it does |
| - | - |
| `channel_id`, `platform`, `storage`, `getCustomer` | Required. `storage` can be async (AsyncStorage in React Native). |
| `currency` | ISO 4217 code. An invalid code is reported with `onWarning` and ignored. Without it, the merchant currency from preferences is used. There is no `USD` default. |
| `sessionMs` | Session length. The merchant currency is still read when you pass it. |
| `consent` | Function read on every event until you call `setConsent()`. |
| `onError`, `onWarning` | Receive destination failures and dropped events. They default to `console.error` and `console.warn`. |
| `flushAt`, `flushIntervalMs`, `flushOnHide`, `appState` | When the queue is sent. See [Sending the queue](#sending-the-queue). |
| `hash` | SHA-256 for personal data sent to Meta and TikTok. |
| `storagePrefix` | Storage key prefix. Use a different one for each `Analytics` instance. |

Calls to `track()` made before `configure()` are kept (up to 100) and sent once it runs, with their original time.

## Track events

```typescript theme={null}
await analytics.track("add_to_cart", { product_id: "p1", quantity: 2, value: 2.3 });
await analytics.track({ name: "purchase", properties: { order_id, value, items } });
```

Catalog events (for example `add_to_cart`, `purchase`, `login`) get the name each destination expects (`view_item` in GA4, `AddToCart` in Meta). Every param you pass reaches the destinations, not only the ecommerce fields. When you pass `product_id` without `items`, the SDK builds `items` for you. Amounts are sent exactly as you pass them: the SDK never rounds `value` or prices.

A catalog event that a destination does not receive (for example `page_view` in React Native) is skipped for that destination.

### What Fire Spark stores

Every event reaches the destinations. Fire Spark stores these:

* Funnel events: `menu_viewed`, `product_viewed`, `add_to_cart`, and `purchase`.
* Interaction events: `product_visited` and `category_visited`.
* Any event sent with the object form, `track({ name, properties })`.

`track("name", params)` with any other name goes only to the destinations. This is by design: use the object form when you also want the event in Fire Spark.

Fire Spark keeps **one event per funnel step per session**, because its funnel metrics count sessions that reached each step. Destinations still receive every occurrence. For example, two `product_viewed` in the same session are two `view_item` in GA4 and one stored event.

Events tracked before there is a customer reach the destinations right away and stay in the queue. They are sent to Fire Spark once `getCustomer()` returns one.

### Choose destinations per call

```typescript theme={null}
await analytics.track("login", { method: "google" }, { only: ["ga4"] });
```

`only` and `exclude` take provider ids. A provider in `only` that you did not add is reported with `onWarning`; the call does not reject.

## Sending the queue

The SDK sends the queue to Fire Spark on its own:

* When it holds `flushAt` events (default 20).
* `flushIntervalMs` after an event is queued (default 30 seconds). `0` turns this off.
* On web, when the page is hidden (`visibilitychange` and `pagehide`), with `keepalive`. Turn it off with `flushOnHide: false`.
* In React Native, when the app goes to the background, if you pass `appState`:

```typescript theme={null}
import { AppState } from "react-native";

await analytics.configure({ ...options, appState: AppState });
```

`purchase` is sent right away. Call `analytics.flush()` when you need the queue sent at a specific moment.

## User and consent

```typescript theme={null}
analytics.setUser({ id: "user_123", properties: { plan: "gold" } });
analytics.setUser(null); // clears it, for example on sign out

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

`setUser()` reaches every destination: GA4 receives the id as `user_id` and the properties as user properties; Meta and TikTok receive the SHA-256 of the id as `external_id`. Without `setUser()`, a customer that is not anonymous is used as the user.

`setConsent()` overrides the `consent` option and is pushed to every destination, also when consent is revoked:

* `analytics` gates GA4 and Masivo.
* `ads` gates Meta and TikTok.
* Fire Spark is first-party and is not gated.

When you pass `consent` to `configure()`, it is pushed to the destinations on configure. When you pass neither, the SDK does not push a default, so your consent platform keeps control.

## Errors

Destination failures never reject `track()`. They go to `onError` with the provider and event name. A destination that throws does not stop the others.

## Personal data and polyfills

Meta and TikTok receive email and phone hashed with SHA-256. The SDK uses `crypto.subtle` and falls back to a built-in implementation when it is missing (Hermes, or a page not served over HTTPS). Pass `hash` to use your own. If hashing fails, the field is left out and reported with `onWarning`.

Event ids use `crypto.randomUUID` or `crypto.getRandomValues` when available and a fallback otherwise, so `track()` works in React Native without a polyfill.

## Several instances

The functions exported by the package share a default instance. Create an `Analytics` when you need an independent one, with its own queue, session, timers, and destinations:

```typescript theme={null}
import { Analytics } from "@fire-spark/analytics";

const kiosk = new Analytics({ ...options, storagePrefix: "kiosk" });
await kiosk.ready; // rejects if configure() fails
await kiosk.track("menu_viewed");
```


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