# Track storefront events

Send cart and checkout events to Google Tag Manager or your own analytics receiver.

Attach a listener when you create OrbCart in the browser. The cart and checkout tell the listener what happened without waiting for analytics delivery.

```ts
import { createEvents } from "@orbcommerce/storefront-events";
import { createCommerce } from "@orbcart/client";
import { toDataLayer } from "@orbcart/client/ga4";

export const events = createEvents({ ga: toDataLayer() });
export const commerce = createCommerce({ url, key, events });
```

Use one event stream per page, not one per component or cart. With Google Tag Manager installed, configure tags for the GA4 events you want to send. The adapter only pushes to `window.dataLayer`; it does not load the Google tag or manage consent. The cart and checkout emit their facts through the SDK's `cart.checkout()` store. The React checkout reports its forms and steps automatically. The kit's `<Cart>` reports when it comes into view inside `<CartProvider>`; outside the provider, pass `viewCart={bag.viewCart}` from `useCart`. Pass `tellInteraction={bag.tellInteraction}` to standalone forms outside the provider if you want their rejection events. If you build a custom cart view, call `checkout.viewCart?.(cart)` once it has shown the cart.

## Which events can I listen to?

| Event                                                  | What it means                                                             | GA4                 |
| ------------------------------------------------------ | ------------------------------------------------------------------------- | ------------------- |
| `cart.viewed`                                          | The storefront showed the cart                                            | `view_cart`         |
| `cart.line_added`                                      | An addition was confirmed                                                 | `add_to_cart`       |
| `cart.line_removed`                                    | A removal was confirmed                                                   | `remove_from_cart`  |
| `cart.line_changed`                                    | A quantity change was confirmed                                           | —                   |
| `cart.code_entered`, `cart.gift_card_entered`          | A code was tried; only the result is reported                             | —                   |
| `checkout.started`                                     | Checkout opened with an open cart                                         | `begin_checkout`    |
| `checkout.step_entered`, `checkout.step_completed`     | The kit showed a step or saved the regions it holds                       | —                   |
| `checkout.shipping_chosen`                             | The runtime confirmed the chosen shipping method                          | `add_shipping_info` |
| `checkout.payment_chosen`                              | The buyer chose an available payment method, or submitted the default one | `add_payment_info`  |
| `checkout.refused`                                     | The runtime refused a checkout operation                                  | —                   |
| `checkout.order_requested`                             | The buyer submitted a quote for purchase                                  | —                   |
| `checkout.payment_failed`                              | A payment failed or was canceled                                          | —                   |
| `checkout.ordered`                                     | A purchase the checkout followed produced an order                        | `purchase`          |
| `product.viewed`                                       | Your storefront showed a product                                          | `view_item`         |
| `product_list.viewed`                                  | Your storefront showed a product list                                     | `view_item_list`    |
| `product.selected`                                     | Your storefront selected a product from a list                            | `select_item`       |
| `ui.pressed`, `ui.opened`, `ui.closed`, `ui.submitted` | A named button, disclosure, or form was used                              | —                   |
| `ui.rejected`                                          | The kit or your storefront reported a form refusal                        | —                   |

A cart mutation that cannot be attributed to the current step from consecutive cart answers is omitted rather than guessed. Browser analytics is best effort: keep using [signed order events](/docs/integrate/order-events) for fulfillment, finance, or reconciliation.

## Customize

### Name an element or tell a product fact

Use stable names, not labels or translations. Buttons, native disclosures, and forms with `data-part` report interactions automatically. Ancestors with `data-scope` put the same part in different places without changing its name. Put a scope on your own cart drawer or modal to distinguish it from the same kit component on a page.

```html
<section data-scope="product-page">
  <button data-part="size-guide">Size guide</button>
</section>
```

That button reports `part: "size-guide"` and `path: ["product-page", "size-guide"]`. If you open your own dialog, tell `ui.opened` yourself and pass `{ from: trigger }` to read the path from the trigger. On a product page, tell the standard product fact once the page shows it. Product prices use decimal major units.

```ts continues
events.tell({
  type: "product.viewed",
  data: {
    reference: "PACK-30",
    title: "30 L Backpack",
    price: { value: 89.9, currency: "EUR" },
  },
});
```

### Send a filtered stream with consent

A listener is either a function that takes an ordered batch or an object with `run`, `types`, and `when`. Leave out `types` for all events. Use a full event name or a prefix such as `checkout.*`.

```ts
import { createEvents, toEndpoint } from "@orbcommerce/storefront-events";

const events = createEvents({
  warehouse: {
    run: toEndpoint("https://collect.example.com/events"),
    types: ["cart.*", "checkout.*", "ui.rejected"],
    when: () => banner.allows("analytics"),
  },
});

// Call this whenever the banner answer changes.
banner.onChange(() => events.flush());
```

The SDK reads `when` when an event is told and again before delivery. Keep it a cheap, synchronous read of your banner state. Return `true` to send, `false` to drop, or `undefined` to hold in memory while the banner is unanswered. On page exit a final batch may start before an older request finishes. Deduplicate by event ID and use sequence rather than arrival order. A closed page loses its unsent events. A network listener should respect the delivery's abort signal; it is aborted after five seconds. Keep custom listeners asynchronous if they do expensive or slow work: synchronous code blocks the browser's main thread even when scheduled in the background.

Your collector receives a JSON array. An event has an `id`, `type`, `time`, `sequence`, and `source`; cart events also carry their cart ID as `subject`. Deduplicate retries by `id`. OrbCart sends no buyer-entered values or tokens; the GA4 coupon is the merchant's discount ID, never the entered code. You are responsible for values in your own events and listener mappings.

### Rename GA4 events or map your own facts

Declare your own event names and payloads once, then pass the type to both the event stream and the adapter. The `ui`, `product`, `product_list`, `cart`, and `checkout` prefixes are reserved.

```ts
import { createEvents } from "@orbcommerce/storefront-events";
import { toDataLayer } from "@orbcart/client/ga4";

type ShopEvents = { "wishlist.added": { reference: string } };

const events = createEvents<ShopEvents>({
  ga: toDataLayer<ShopEvents>({
    names: { view_cart: "shop_cart_opened" },
    map: {
      "wishlist.added": ({ data }) => ({
        event: "add_to_wishlist",
        ecommerce: { items: [{ item_id: data.reference }] },
      }),
    },
  }),
});

events.tell({ type: "wishlist.added", data: { reference: "PACK-30" } });
```

## Next steps

| Read                                                   | When                                                      |
| ------------------------------------------------------ | --------------------------------------------------------- |
| [Set up checkout](/docs/shop/react-checkout)                | You want to put the checkout on your storefront.          |
| [Receive signed order events](/docs/integrate/order-events) | Your backend needs a reliable record of financial events. |