# Tracking events with the SDK

> Current Froomle documentation · [View canonical page](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html)

Use this guide to decide who sends each event, track the current page or finished cards, and send application events such as purchases and subscriptions.

<a id="EventTracking"></a>

## Who sends each event?

| Implementation choice | Auto event tracking | What you need to do |
| --- | --- | --- |
| Declarative (`data-froomle-…​`) | Yes | Page events (`page_visit`, `detail_pageview`) do not require a recommendation block. The SDK tracks eligible impressions and clicks on recommendation cards it registers. For finished cards rendered by your own application, see [Tracking server-rendered recommendations](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#server-rendered-recommendation-tracking). Send [subscription conversions](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#SubscriptionConversionEvents) from confirmed business callbacks. |
| React bindings (`@froomle/frontend-sdk/react`) | Page events and SDK-registered recommendation cards | Mount `FroomleSdkInit` for page-level events, and render SDK recommendation handles or entries through `FroomleReco` for automatic recommendation tracking. For cards rendered without that wrapper, send recommendation events explicitly. Send business events from confirmed application callbacks. |
| Programmatic (JS/TS API) | No | Initialize shared SDK state first, then send page and business events explicitly. If you request recommendations and render your own UI, use [`sendEvent`](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#send-event) for recommendation impressions and clicks. |

All event types and payloads must follow the [Event Model and Tracking Contract](https://docs.froomle.com/froomle-doc-main/v2/guide/topics/tracking-events.html). If the SDK does not own event delivery, use [Manual Event Integration](https://docs.froomle.com/froomle-doc-main/v2/guide/manual-integration/events.html) instead.

Initialized DOM integrations and mounted `FroomleSdkInit` automatically recover the current page event and re-observe currently visible, resolved recommendation placements after consent permits tracking. Forward the CMP state through `setConsent(…​)`; do not add manual tracking workarounds to an automatic consent callback. Pure programmatic integrations call `trackCurrentPage()` and recommendation event helpers explicitly. See [Automatic tracking after consent changes](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#consent-page-recovery).

<a id="server-rendered-recommendation-tracking"></a>

## Tracking server-rendered recommendations

What matters is who fills the cards, not where the HTML comes from.

-   If your server renders placeholders and the browser SDK fills and registers them, the SDK tracks eligible impressions and clicks automatically. The same applies to original CMS cards the SDK keeps and registers with valid item identity and request attribution.
    
-   If your server fetches recommendations and renders finished cards, your application sends recommendation impressions and clicks explicitly. The same applies when a browser application calls `getRecommendations(…​)` and renders its own cards without an SDK tracking component.
    

There is no automatic tracking option for finished server-rendered cards. The SDK did not make their recommendation request, so it cannot tell from HTML attributes whether the request used the same visitor identity and experiment group as the browser SDK. A request ID identifies the result; it does not set the browser’s identity or group.

Page tracking is independent. A configured automatic SDK integration can still send `page_visit` or `detail_pageview` when consent permits, even if your application handles all recommendation events.

Before sending events for finished cards, configure the browser SDK with the same Froomle environment and [consent-permitted device and account identity](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#Users) as the recommendation request. If your application assigns the experiment group, [register the same group](https://docs.froomle.com/froomle-doc-main/v2/js_lib/benchmarking.html#BenchmarkConfig) before SDK initialization. Do not reuse a withdrawn identity or the previous account’s identity to match an older request.

Pass the displayed item’s ID and type, the placement’s list name, and the original response’s `request_id` to your tracking code. Connect the example functions to your visibility and click handlers; do not record an impression just because the server rendered the card.

```ts
import { sendEvent } from '@froomle/frontend-sdk'

const itemId = 'article-123'
const itemType = 'article'
const attribution = {
  list_name: 'recommended_for_you',
  request_id: 'req-456',
}

function onRecommendationVisible() {
  sendEvent(itemId, itemType, 'impression', attribution)
}

function onRecommendationClick() {
  sendEvent(itemId, itemType, 'click_on_recommendation', attribution)
}
```

The SDK uses the current consent, identity, and assignment when it sends these events. Do not try to override identity or group in the event payload. Events blocked by consent are not queued for replay. Use one tracking path per card to avoid duplicate impressions and clicks. See [`sendEvent`](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#send-event) for the SDK contract, or [Manual event integration](https://docs.froomle.com/froomle-doc-main/v2/guide/manual-integration/events.html) if you send events directly without the SDK.

<a id="PageTrack"></a>

## Detail Context and Page Tracking

For detail pages, set context item (and optional type):

```ts
import { setContextItem, setContextItemType, setPageVisit } from '@froomle/frontend-sdk'

setPageVisit('article_detail')
setContextItem('sample_item_id_2')
setContextItemType('article')
```

Script-tag equivalent:

```html
<script
  src="https://cdn.jsdelivr.net/npm/@froomle/frontend-sdk@latest/dist/froomle.global.js"
  data-froomle-env="sample_env"
  data-froomle-page-visit="article_detail"
  data-froomle-context-item="sample_item_id_2"
  data-froomle-context-item-type="article"
></script>
```

Behavior notes:

-   `context_item_type` is optional; when omitted and `context_item` is set, SDK defaults it to `article`.
    
-   `setContextItem(…​)` and `setContextItemType(…​)` only define the detail-page context. They do not send `detail_pageview` by themselves.
    
-   The same context (`context_item` / `context_item_type`) is used for recommendation requests and detail tracking.
    
-   When `context_item_type` is omitted, `detail_pageview.action_item_type` also defaults to `article`.
    
-   Automatic `detail_pageview` requires the page-level SDK init pipeline to run on that page.
    
    -   Script-tag/global integrations get this from the normal SDK bootstrap on the detail page.
        
    -   React/framework integrations get this from mounting `FroomleSdkInit` on the detail page.
        
    
-   When `context_item` is present and the page-level init pipeline runs with event consent, SDK emits `detail_pageview` for the page and suppresses the generic `page_visit` event.
    
-   If you only need article tracking on a detail page, you can still initialize the SDK there without rendering any recommendation blocks.
    
-   Consent changes after automatic initialization update current-page and registered recommendation tracking through the consent setter alone. See [Automatic tracking after consent changes](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#consent-page-recovery).
    
-   Set the final page type and detail context before initialization or consent recovery runs. Synchronous setters in the same callback are coalesced before automatic dispatch; the SDK cannot wait for an item context your application has not supplied yet.
    

<a id="track-current-page"></a>

### Explicit current-page tracking

Use `trackCurrentPage()` for pure programmatic integrations, an explicit retry, or a client-side route change after the new page context is configured. It selects `detail_pageview` when a context item exists, otherwise `page_visit`.

The helper and automatic DOM/React tracking share one active page record:

-   A successful call is deduplicated for the current URL (excluding its fragment), page type, context item/type, and consent period.
    
-   Concurrent calls share delivery. Actual consent changes start a new period; repeated consent values do not.
    
-   A different URL or page context establishes a new active page. Returning to a previous route after tracking another route is a new observation, not a permanent tab-wide suppression.
    
-   A consent-blocked call or a call without `page_type` does not consume delivery. Fix the missing state and call again. A rejected transport attempt also remains retryable.
    
-   This is not a router listener. Changing URL or context after a successful send does not automatically send another page event; your router must invoke tracking for the new page. Recovery on a later consent elevation always uses the then-current URL/context.
    
-   The helper does not fetch, fill, or reprocess recommendation placements. Raw manual `sendEvent(…​)` calls do not participate in this deduplication.
    

Pure programmatic example, after the environment and page context have been configured and your CMP mapping permits level 2:

```ts
import { trackCurrentPage } from '@froomle/frontend-sdk'

// Call after forwarding the visitor's actual consent choice to the SDK.
await trackCurrentPage()
```

| Result | Meaning |
| --- | --- |
| `sent` | The SDK transport completed the page-event send. Verify backend ingestion separately when testing end-to-end delivery. |
| `already-tracked` | This active URL/context/consent period was already sent successfully. |
| `consent-required` | Consent does not currently permit events. No send occurred. |
| `missing-page-type` | Configure `setPageVisit(…​)` before retrying. No send occurred. |
| Rejected promise | Transport delivery failed; handle the error and retry when appropriate. |

<a id="_manual_event_helpers"></a>

## Manual Event Helpers

Use the dedicated helper functions for the common manual/programmatic flows the SDK now models explicitly.

```ts
import {
  setSiteContext,
  setSubscriptionLevel,
  sendAddToCart,
  sendCancelSubscription,
  sendItemInteraction,
  sendPurchase,
  sendRemoveFromCart,
  sendStartSubscription,
  sendUserInteraction
} from '@froomle/frontend-sdk'

setSiteContext('shop.example.com')
setSubscriptionLevel('SUBSCRIPTION')

// Uses current context_item / context_item_type from SDK state
sendItemInteraction('product_like')

sendUserInteraction('submit_review')

sendAddToCart(2, {
  basket_content: [{ id: 'product-111' }, { id: 'product-987' }]
})

sendRemoveFromCart(1, {
  basket_content: [{ id: 'product-111' }]
})

sendPurchase(2, 19.99, {
  original_price: 29.99
})

sendStartSubscription('digital', {
  conversion_source: 'paywall'
})

sendCancelSubscription('digital', {
  cancellation_reason: 'customer_request'
})
```

> **IMPORTANT:**
> 
> -   These helper functions use the same runtime defaults as `sendEvent(…​)`: `page_type`, `channel`, effective `site_context`, configured `subscription_level`, current-URL UTM fields, current-page URL and referrer source fields, `device_id`, `user_id`, and `user_group` are read from SDK state when available.
>     
> -   For item-based helpers (`sendItemInteraction`, `sendAddToCart`, `sendRemoveFromCart`, `sendPurchase`), omit `actionItem` / `actionItemType` to reuse the current `context_item` / `context_item_type`.
>     
> -   If you pass explicit `actionItem` / `actionItemType`, those values win over context.
>     
> -   If an item-based helper has neither explicit item args nor current context, it does not emit an event.
>     
> -   Both subscription helpers reuse configured `context_item` / `context_item_type` when available, but still emit an itemless lifecycle event when no item context exists. Explicit `extras` values override inferred context.
>     
> -   Use these helpers for `item_interaction`, `user_interaction`, `add_to_cart`, `remove_from_cart`, `purchase`, `start_subscription`, and `cancel_subscription`.
>     
> -   Keep `sendEvent(…​)` for unsupported/custom event types or when you need total payload control.
>     

<a id="SubscriptionConversionEvents"></a>

## Subscription Conversion Events

`sendStartSubscription(subscriptionType, extras?)` and `sendCancelSubscription(subscriptionType, extras?)` are explicit business-event helpers. Call them only after your application has confirmed that the subscription started or was cancelled. Do not infer a conversion from a paywall, checkout, account-page, or cancellation-link click: the user may abandon or the operation may fail.

The helpers are available from the root npm package in JS/TS and React applications, and from `window.FroomleFrontendSdk` in script-tag integrations. They supplement declarative DOM tracking: automatic `page_visit`, `detail_pageview`, `impression`, and `click_on_recommendation` behavior continues unchanged. There is no declarative HTML attribute that represents a confirmed subscription conversion.

Module/React application callback:

```ts
import {
  sendCancelSubscription,
  sendStartSubscription
} from '@froomle/frontend-sdk'

async function confirmSubscription() {
  await subscriptionApi.start()
  sendStartSubscription('digital', {
    conversion_source: 'article-paywall'
  })
}

async function confirmCancellation() {
  await subscriptionApi.cancel()
  sendCancelSubscription('digital', {
    cancellation_reason: 'customer_request'
  })
}
```

Declarative DOM/script-tag application callback, after the SDK has initialized:

```html
<script>
  function onSubscriptionConfirmed() {
    // This callback runs after froomle:init and a confirmed business outcome.
    window.FroomleFrontendSdk.sendStartSubscription('digital', {
      conversion_source: 'article-paywall'
    })
  }

  function onCancellationConfirmed() {
    // This callback runs after froomle:init and a confirmed business outcome.
    window.FroomleFrontendSdk.sendCancelSubscription('digital', {
      cancellation_reason: 'customer_request'
    })
  }
</script>
```

> **IMPORTANT:**
> 
> -   `subscriptionType` is required by both SDK helpers. Use a stable agreed value such as `digital`, `physical`, or `newsletter`.
>     
> -   The helpers reuse SDK-managed page, channel, identity, consent, enrichment, and navigation-safe event transport behavior.
>     
> -   At consent level `0`, the SDK does not emit the event. At consent level `1`, it emits anonymously. At consent level `2`, it includes identified SDK state when available.
>     
> -   On detail pages, configured `context_item` / `context_item_type` are included when available. On home, checkout, account, and other itemless pages, the event is still valid and is sent without item context.
>     
> -   Pass `context_item` and `context_item_type` in `extras` when deliberate event context differs from the current page context. Explicit extras are authoritative.
>     
> -   `subscription_level` is the visitor’s current entitlement state. It does not replace `subscription_type` and changing it does not emit a conversion event automatically.
>     

<a id="_retail_trigger_based_events"></a>

## Retail Trigger-Based Events

For retail flows, wire the dedicated helper functions directly to the business trigger in your UI code. Do not rely on generic click tracking for these events.

Typical examples:

-   `sendAddToCart(…​)` from an Add to Cart button or cart form submit.
    
-   `sendRemoveFromCart(…​)` from a remove-line action in the basket.
    
-   `sendPurchase(…​)` from the confirmed checkout or thank-you step, not from the initial buy button.
    
-   `sendItemInteraction(…​)` for actions such as wishlist, favorite, or compare.
    
-   `sendUserInteraction(…​)` for non-item flows such as review submit, quote request, or starting a chat.
    

```tsx
import {
  sendAddToCart,
  sendItemInteraction,
  sendPurchase,
  sendRemoveFromCart,
  sendUserInteraction,
  setContextItem,
  setContextItemType,
  setPageVisit,
  setChannel
} from '@froomle/frontend-sdk'

setPageVisit('product_detail')
setChannel('www-desktop')
setContextItem('32636759')
setContextItemType('product')

buttonAddToCart.onclick = () => {
  sendAddToCart(2, {
    basket_content: [{ id: '32636759' }],
    merchandising_slot: 'product-detail'
  })
}

buttonWishlist.onclick = () => {
  sendItemInteraction('product_like', {
    source: 'product-detail'
  })
}

buttonReview.onclick = () => {
  sendUserInteraction('submit_review', {
    review_surface: 'product-detail'
  })
}

buttonRemoveFromCart.onclick = () => {
  sendRemoveFromCart('32636759', 'product', 1, {
    basket_content: []
  })
}

confirmPurchase.onclick = () => {
  sendPurchase(1, 119.99, {
    original_price: 149.99,
    checkout_id: 'checkout-2048'
  })
}
```

Retail helper guidance:

-   Prefer the dedicated helper matching the business action instead of raw `sendEvent(…​)`.
    
-   Set `context_item` / `context_item_type` on product-detail pages when you want the short helper forms.
    
-   Use explicit item args when the triggered item differs from the current page context, such as a basket line or variant selector.
    
-   `extras` is merged last, so add flow-specific fields such as `basket_content`, `original_price`, `checkout_id`, or `merchandising_slot` there.
    
-   For manually tracked recommendations, use `sendEvent(…​)` with the displayed item’s identity, `list_name`, and `request_id`. The SDK handles group attribution from its configured assignment.
    

<a id="send-event"></a>

## `sendEvent`

Use `sendEvent(…​)` when you need explicit control over an event type or payload that is not covered by the dedicated helper functions.

```ts
import { sendEvent } from '@froomle/frontend-sdk'

sendEvent('sample_item_id_1', 'article', 'impression', {
  list_name: 'recommended_for_you',
  request_id: 'req-id'
})
```

When you need to send a separate manual event for a card currently registered by the SDK, you can infer missing attribution from its element. Do not send an extra manual impression or recommendation click for a card that already tracks those events automatically.

```ts
sendEvent(undefined, undefined, 'item_interaction', { interaction_type: 'save' }, {
  source: savedCardElement
})
```

> **TIP:**
> 
> Need the full event contract (event types, required fields, and attribution rules)? See [Event Model and Tracking Contract](https://docs.froomle.com/froomle-doc-main/v2/guide/topics/tracking-events.html).
> 
> For email/newsletter campaign click attribution through the browser SDK, see [Email Campaign Recommendation Attribution with the SDK](https://docs.froomle.com/froomle-doc-main/v2/js_lib/email-campaign-attribution.html).

> **IMPORTANT:**
> 
> -   You normally should not need `sendEvent(…​)` for standard e-commerce triggers. For first-party support of retail flows, use the dedicated helpers from [Retail Trigger-Based Events](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#_retail_trigger_based_events) instead: `sendItemInteraction(…​)`, `sendUserInteraction(…​)`, `sendAddToCart(…​)`, `sendRemoveFromCart(…​)`, and `sendPurchase(…​)`.
>     
> -   For confirmed subscription lifecycle conversions, use `sendStartSubscription(…​)` and `sendCancelSubscription(…​)` from [Subscription Conversion Events](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#SubscriptionConversionEvents) instead of constructing these events with `sendEvent(…​)`.
>     
> -   `sendEvent` auto-populates base fields from SDK runtime state: `event_type`, `page_type`, `channel`, effective `site_context`, configured `subscription_level`, current-URL UTM fields, current-page URL and referrer source fields, `device_id`, and (when available) `user_id` and `user_group`.
>     
> -   `action_item` / `action_item_type` come from the call, but if the runtime receives `undefined` values in JS it falls back to `context_item` / `context_item_type` when present.
>     
> -   `page_visit` is page-level. It does not require `action_item` / `action_item_type`, so manual programmatic integrations can call `sendEvent(undefined, undefined, 'page_visit')` (or `null` in plain JS) after setting `page_type` through SDK state. For current-page observations, prefer [`trackCurrentPage()`](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#track-current-page); raw `sendEvent(…​)` does not share automatic page-event deduplication.
>     
> -   `extras` is merged last. Use it to add fields such as `list_name` or `request_id`, or to intentionally override default fields (for example `page_type`, `channel`, `site_context`, `subscription_level`, `utm_source`, or `page_url`, `referrer_url`, or `referrer_domain`) in custom flows.
>     
> -   `options.source` can fill missing `action_item`, `action_item_type`, `list_name`, and `request_id` from a current SDK-registered card. Finished cards with copied attributes and cards from an earlier tracking cycle cannot supply those fields.
>     
> -   If a recommendation impression or click needs inferred fields and the SDK cannot find a current card or an explicit field conflicts with its attribution, the SDK does not send the event and records the reason in diagnostics. When all four fields are explicit, attribution does not depend on the element.
>     
> -   Programmatic/manual event delivery uses navigation-safe transport defaults in the browser (`keepalive` with beacon fallback when needed). You do not pass transport flags through `extras`.
>     
> -   Script-tag attributes are bootstrap inputs for SDK state; they are not per-event arguments to `sendEvent(…​)`.
>     
> -   For programmatic integrations, event payloads and event types must follow [Event Model and Tracking Contract](https://docs.froomle.com/froomle-doc-main/v2/guide/topics/tracking-events.html).
>     

`extras` requirement guide:

| Field in `extras` | Requirement |
| --- | --- |
| `list_name`, `request_id` | For recommendation-related events (`impression`, `click_on_recommendation`), treat these as required for reliable attribution/reporting. For non-recommendation events, they are optional. |
| `user_group` | Do not set per event. The SDK sends the group registered before initialization for external assignment and omits it for Froomle assignment. It does not copy the response group or model `version` into the event. |
| `user_id` | Do not set per event. Supply the active account with `setUserId(…​)` or the script-tag setting. The SDK includes it only at consent level 2. |
| `page_type`, `channel` | Optional overrides only. The SDK already sets these from runtime state. |
| `device_id` | Do not set per event. The SDK uses the current device ID according to the [identity and consent settings](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#Users). |

<a id="ROCB"></a>

## Event Tracking Behavior

The SDK automatically tracks eligible impressions and clicks for cards it registers through declarative recommendations, Smart Sort, or React’s `FroomleReco`. This includes original CMS cards when the SDK keeps and registers them with valid identity and request attribution.

> **IMPORTANT:**
> 
> If you send events manually through the SDK, adhere to [Event Model and Tracking Contract](https://docs.froomle.com/froomle-doc-main/v2/guide/topics/tracking-events.html).

Practical rule:

-   Send [recommendation impressions and clicks](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#send-event) yourself for [finished server-rendered cards](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#server-rendered-recommendation-tracking) or cards your app renders outside an SDK tracking component. Pass the displayed item ID and type, `list_name`, and the original `request_id`.
    
-   Send confirmed subscription starts and cancellations explicitly with `sendStartSubscription(…​)` or `sendCancelSubscription(…​)`. A DOM click does not confirm a conversion.
    

Item identity in automatic events:

-   `detail_pageview` uses the page’s context item and defaults its type to `article`.
    
-   An automatic recommendation impression and click use the same registered card ID and item type. For returned recommendations, the SDK uses a valid response `item_type`, then the placement’s `data-froomle-item-type`, then `article`. For original cards, provide the original card’s identity.
