> For the complete documentation index, see [llms.txt](https://docs.liquidcommerce.cloud/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.liquidcommerce.cloud/elements-v2/advanced.md). Agents can also search and read this documentation through its [MCP server](https://docs.liquidcommerce.cloud/~gitbook/mcp).

# Advanced

Configuration and platform topics beyond the core components: theming, analytics, telemetry, error handling, browser support, proxy setup, and SSR. Each section below is the full detail for its topic — where a topic has its own dedicated page (theming, configuration), this page links to it instead of duplicating it.

## Theming

Match Elements to your brand with the `customTheme` config: colors, fonts, corner radius, and per-component layout. `customTheme` has a `global` block (`theme` + `layout`) plus optional per-component blocks (`product`, `address`, `cart`, `checkout`, `productList`) — each deep-partial, so you only set the keys you want to override on top of your account's server-configured default theme. The same object can also be delivered via the CDN, as JSON in a `<script data-liquid-commerce-elements-custom-theme type="application/json">` tag (invalid JSON is logged and ignored).

Full per-component key tables, visual behavior, and copy-paste examples: [Theming](https://docs.liquidcommerce.cloud/elements-v2/theming.md) (canonical reference) · [Configuration](https://docs.liquidcommerce.cloud/elements-v2/configuration.md).

## Promo Ticker

The scrolling promo ticker is also configurable programmatically via the `promoTicker` config key — not just through the `data-promo-*` script attributes.

```js
const client = await Elements('YOUR_API_KEY', {
  env: 'production',
  promoTicker: [
    {
      promoCode: 'SUMMER20',
      text: ['20% Off', 'Free shipping over $50'],
      separator: '•',
      activeFrom: '2026-06-01T00:00:00Z',
      activeUntil: '2026-08-31T23:59:59Z'
    }
  ]
});
```

Each entry: `promoCode` (string), `text` (array of ticker messages), `separator` (string shown between messages), and `activeFrom`/`activeUntil` (ISO 8601 UTC date strings — `activeFrom` must be earlier than `activeUntil`). Unlike the single-entry `data-promo-*` attributes, `promoTicker` accepts an array of entries; each is validated independently, and an entry that's missing a field or has an invalid date range is dropped (with a console warning) rather than breaking the whole config.

This mirrors the data-attribute promo ticker documented in the [Quick Start Guide](https://docs.liquidcommerce.cloud/elements-v2/quick-start-guide.md).

## Analytics (Google Tag Manager)

Elements ships built-in GTM / GA4 tracking. It's automatic — the SDK injects the GTM container script, wires up `window.dataLayer`/`window.gtag`, and pushes GA4 ecommerce events. There's no host-side setup.

* **Production and staging.** GTM initializes in `production` and `staging`; it stays silent in Builder mode. Container IDs and enable flags come from server-driven config, not your `Elements(...)` config.
* **Non-destructive.** `window.dataLayer` is created only if absent and `window.gtag` is defined only if you don't already have one; an existing partner container on the page is detected and reused rather than re-loaded.
* **Container injection.** The container script loads from `https://www.googletagmanager.com/gtm.js?id=<containerId>`, appended to `<head>` as `async` with `crossorigin="anonymous"`; the SDK waits for the container to initialize before flushing any queued events.
* **Event queueing.** Events fired before GTM finishes initializing are queued (capped at 100, oldest dropped first) and flushed once the container is ready; anything still queued more than 30 seconds later is discarded rather than sent stale.
* **Dual-container.** Events target the LiquidCommerce container **and** your partner container via GA4 `send_to` (only initialized containers are included). If the LiquidCommerce container fails to load, the SDK falls back — in order — to the partner container, any other initialized GTM container already on the page, or the basic `dataLayer`, so tracking degrades gracefully instead of failing outright.
* **Source tracking.** Every event also carries `tenant_name` (partner name), `tenant_code` (partner code), `tenant_env` (SDK environment), and `tenant_source` (the SDK package `description` string plus its version, e.g. `<description> v<version>`).

### Events

The standard ecommerce events are GA4-shaped: each carries an `items[]` array, and most also include `value` and `currency` (always `USD`) — the exceptions are `select_item` (no `value`/`currency`) and `view_item_list` (`currency` but no `value`). `coupon` is added on the checkout events (`begin_checkout`, `add_shipping_info`, `add_payment_info`, `purchase`), and `purchase` additionally carries `transaction_id`, `tax`, and `shipping`. The custom events listed further below do **not** use this ecommerce shape — they carry their own fields (e.g. `promo_code`, `gift_card_code`, address/product identifiers).

**Standard GA4 ecommerce events**

| Event               | Fired when                              |
| ------------------- | --------------------------------------- |
| `view_item`         | A shopper views a product               |
| `view_item_list`    | A shopper views a list of products      |
| `select_item`       | A shopper selects a product from a list |
| `add_to_cart`       | A shopper adds an item to the cart      |
| `view_cart`         | A shopper views the cart                |
| `remove_from_cart`  | A shopper removes an item from the cart |
| `begin_checkout`    | A shopper begins checkout               |
| `add_shipping_info` | Shipping info is added during checkout  |
| `add_payment_info`  | Payment info is added during checkout   |
| `purchase`          | A purchase completes                    |

**Custom events**

| Event                                                             | Fired when                                                      |
| ----------------------------------------------------------------- | --------------------------------------------------------------- |
| `promo_code_attempt` / `promo_code_applied` / `promo_code_failed` | A promo code is submitted / successfully applied / rejected     |
| `gift_card_attempt` / `gift_card_applied` / `gift_card_failed`    | A gift card is submitted / successfully applied / rejected      |
| `address_updated` / `address_failed`                              | An address is successfully updated / an address operation fails |
| `product_no_availability`                                         | A product has no availability for any size or fulfillment       |
| `product_size_no_availability`                                    | A selected size has no availability                             |
| `product_fulfillment_no_availability`                             | A selected fulfillment type has no availability                 |

These GTM/GA4 events are separate from the SDK's own `lce:*` browser [events](https://docs.liquidcommerce.cloud/elements-v2/events.md) — GTM events feed ad/analytics platforms; `lce:*` events are for your own JS listeners.

## Telemetry & Privacy

The SDK batches internal warning/error events and sends them to `<baseUrl>/api/telemetry` so LiquidCommerce can monitor SDK health. It's designed to avoid blocking or breaking your app.

* **When it runs:** only when `env` is `production` **and** no custom API URL is set (`hasCustomApiUrl` is `false`). Otherwise disabled — no timer, no capture, no send (also inert during SSR). Only `warn`/`error`/`fatal` events are captured; debug/log/info are excluded.
* **Batch sizing:** flushes when the queue reaches **5 events**, on a **5-second timer**, or on page teardown (`beforeunload`/`pagehide`) — whichever comes first. The queue itself is capped at **50 events**; if it overflows, the oldest events are dropped first.
* **Delivery:** payloads are sent as `text/plain` via `navigator.sendBeacon`, falling back to a synchronous `XMLHttpRequest` that can briefly block the main thread if `sendBeacon` is unavailable or fails.
* **What's in each event:** SDK context (version, env, `isBuilder`, `partnerCode`), user context (`deviceId`, `isLocalStorageAvailable`, and the user's **selected formatted address**), browser context (`userAgent`, device type, URL, referrer, timezone), and — for errors — name/message/code and a stack truncated to the first 10 lines.
* **Batch payload shape:**

```ts
interface TelemetryBatch {
  batchId: string;
  timestamp: number;
  events: Array<{
    eventId: string;
    timestamp: number;
    level: 'warn' | 'error' | 'fatal';
    message: string;
    context?: string;
    error?: { name: string; message: string; stack?: string; code?: string | number };
    metadata: {
      sdk: { version: string; env: string; isBuilder: boolean; partnerCode?: string };
      user: { deviceId: string; isLocalStorageAvailable: boolean; selectedAddress?: string };
      browser: { userAgent: string; deviceType: string; url: string; referrer?: string; timezone?: string };
    };
  }>;
}
```

* **Turning it off:** run in a non-production environment, or set a custom API URL (`development.customApiUrl`), which disables telemetry regardless of environment.

## Error Handling

The SDK surfaces failures two ways, and also installs global handlers — plan your monitoring accordingly.

```ts
class SDKError extends Error {
  constructor(message: string, reThrow?: boolean);
  name: 'SDKError';
  isSdk: boolean;
  reThrow: boolean;
}
```

* **Init failure returns `null`** — this isn't limited to SSR (see Server-Side Rendering, below): in the browser, `Elements()`, `ElementsBuilder()`, and `ElementsCheckout()` also resolve to `null` (never reject) when initialization itself fails — e.g. an invalid API key or an auth error — so always null-check the client before using it. See [Overview](https://docs.liquidcommerce.cloud/elements-v2/overview.md) for the canonical pattern.
* **`SDKError`** — structural input errors throw a catchable `SDKError` (`name: 'SDKError'`, `isSdk: true`), e.g. passing a non-array or an empty array to `injectProductElement`. Most action failures, though, resolve rather than throw and emit a `*_failed` event instead — a well-formed entry with an invalid product identifier does **not** throw; it renders an error view inside the component and sets an error in the store. So wrap calls in `try/catch` **and** listen for the matching event.
* **Failure events** — listen on `window` for `lce:actions.*_failed` (`address_failed`, `cart_failed`, `cart_product_add_failed`, `cart_promo_code_failed`, `checkout_failed`, `checkout_submit_failed`, `checkout_product_add_failed`, `checkout_promo_code_failed`, `checkout_gift_card_failed`). Payload is in `event.detail.data`.
* **Global interception** — on load the SDK reassigns `window.onerror` and `window.onunhandledrejection`. Errors it classifies as SDK-originated (via an `isSDKError` heuristic over message/stack/source) are logged and **suppressed** so they never propagate; everything else is chained to any previously-installed handler. **Implication:** SDK-originated errors will **not** reach host error monitoring (e.g. Sentry), and the heuristic can occasionally match a non-SDK error — rely on the `*_failed` events and `try/catch` to detect failures instead. **Note:** the catchable `SDKError` thrown by actions (the `SDKError` bullet above) is deliberately *excluded* from this suppression — it's constructed with `reThrow`, so an **uncaught** one propagates normally, reaching your code and any previously-installed handler (Sentry, etc.). Only other internal SDK errors are silently suppressed here.
* **Missing container** — `injectAddressElement`, `injectCartElement`, `injectCheckoutElement`, and `injectProductElement` don't throw if the target container ID isn't in the DOM yet — they log a `console.warn` and resolve without injecting (the single-element methods return `null`) instead of throwing, so make sure the container exists before calling these.
* **Account disabled server-side** — distinct from the null-client case above: if Elements is disabled for your account server-side, `Elements()`/`ElementsBuilder()` still initialize successfully, but every `inject*` call renders an "Element Unavailable" card into the target container instead of the real component (no `SDKError`, no `*_failed` event). If your components are all showing this card despite a successful init, contact your LiquidCommerce representative to confirm Elements is enabled for your account.

## Browser Support

Targets modern browsers: Chrome 66+, Firefox 60+, Safari 12+, Edge 79+. These versions are also the baseline for the SDK's other requirements — ES2018 JavaScript and the Fetch API — so no separate polyfill is needed for those two specifically.

* **Hard requirement:** Custom Elements (Web Components) + Shadow DOM. If `window.customElements` or `HTMLElement.prototype.attachShadow` is missing, the SDK logs a console error and exits gracefully (no init, no throw). Add a Web Components polyfill before the SDK script to support older browsers.
* **LocalStorage (optional, recommended).** Used as a fast path for persisting the device ID behind session data (cart/address) across reloads. When it's unavailable — incognito or Safari/Firefox private mode, in-app webviews (Instagram, Facebook, TikTok, etc.), cross-origin iframes — the SDK falls back to a device fingerprint derived from stable, non-invasive characteristics (screen color depth/gamut, pixel ratio, CPU cores, platform, browser engine, timezone). Because the fingerprint is deterministic rather than random, it stays consistent across reloads even without localStorage, and cart/address state is preserved via server-side session persistence.
* **Built-in DOM polyfills:** the SDK auto-applies small polyfills (`replaceChildren`, `prepend`, `remove`/`replaceWith`/`before`/`after`, `Object.fromEntries`), so hosts don't need to. Each is a no-op when the native method exists.
* Always load the SDK script with `defer`.
* Checkout's payment step additionally loads Stripe.js from `js.stripe.com` at runtime — if your CSP is strict, see [Payment (Stripe) requirements](https://docs.liquidcommerce.cloud/elements-v2/checkout.md#payment-stripe-requirements) for the hosts to allow.

## Proxy Setup

Route the SDK's API traffic through a proxy on your own domain to keep requests first-party.

```js
const client = await Elements('YOUR_API_KEY', {
  env: 'production',
  proxy: {
    baseUrl: 'https://yoursite.com/api/elements-proxy/', // absolute, trailing slash required
    headers: { 'X-My-Auth': '...' } // optional, merged into every proxied request
  }
});
```

Your endpoint forwards each request to the upstream Elements API, preserving method, headers, and body. The SDK doesn't hardcode the upstream host — it sends the environment-specific target in the `X-Liquid-Proxy-Target` header (with `X-Liquid-Proxy: true`), so forward to that value. Note: `proxy.baseUrl` reroutes API calls only; setting a **custom API URL** (`development.customApiUrl`) is what disables built-in telemetry.

> `proxy` is config-object only — there's no `data-liquid-commerce-elements-proxy` script attribute, so the declarative CDN auto-init snippet can't set one. If you're using the CDN build, call `window.LiquidCommerce.Elements('YOUR_API_KEY', { proxy: { baseUrl: '...' } })` yourself instead of relying on `data-*` attributes; via npm, pass `proxy` to the imported `Elements()` factory as shown above.

Minimal Express proxy endpoint:

```javascript
import express from 'express';
import fetch from 'node-fetch';

const app = express();
app.use(express.json());

// Mounted at the path of your proxy.baseUrl ('/api/elements-proxy/').
app.all('/api/elements-proxy/*', async (req, res) => {
  const upstream = req.headers['x-liquid-proxy-target'];
  if (!upstream) {
    return res.status(400).send('Missing X-Liquid-Proxy-Target header');
  }

  const forwardedPath = req.params[0]; // e.g. 'api/auth/authenticate'
  const targetUrl = `${upstream}/${forwardedPath}`;

  const response = await fetch(targetUrl, {
    method: req.method,
    headers: { ...req.headers, host: new URL(upstream).host },
    body: ['GET', 'HEAD'].includes(req.method) ? undefined : JSON.stringify(req.body)
  });

  const data = await response.text();
  res.status(response.status).send(data);
});

app.listen(3000);
```

Keep your API key server-side whenever possible, and make sure CORS allows your storefront domain to call the proxy.

## Development Config

Host-only options for local testing and debugging live under `development` in the client config (or the `data-liquid-commerce-elements-development` JSON script tag — see the [Quick Start Guide](https://docs.liquidcommerce.cloud/elements-v2/quick-start-guide.md)).

```js
const client = await Elements('YOUR_API_KEY', {
  env: 'staging',
  development: {
    customApiUrl: 'http://localhost:3000/api',
    openShadowDom: true,
    mockMode: true
  }
});
```

* **`customApiUrl`** — points the SDK at a different API base URL than the one derived from `env` (also disables built-in telemetry, see Telemetry & Privacy above).
* **`openShadowDom`** — use an inspectable (open) Shadow DOM instead of the default closed mode; forced to `false` in production regardless of what's passed.
* **`mockMode`** — sends an `X-Liquid-Api-Mock-Mode` header with every API request so the backend returns mock data instead of live data. Defaults to `false`.

Full reference: [Configuration](https://docs.liquidcommerce.cloud/elements-v2/configuration.md).

## Server-Side Rendering (SSR)

The SDK is browser-only but safe to import in SSR frameworks (Next.js, Nuxt, Remix, SvelteKit) — it resolves to an SSR-safe stub on the server.

* Every factory guards on `typeof window`/`document`: `Elements()`, `ElementsBuilder()`, and `ElementsCheckout()` (from the `/checkout` entry) return `null` server-side and log a warning instead of throwing.
* The package maps its Node condition to dedicated stub builds, so bundlers pick up a no-op module during SSR. Call factories from client-only code (e.g. in a `useEffect`/`onMounted`), after mount, and guard on the possibly-`null` return.

See [Browser Support](#browser-support) above for the full requirements, including the LocalStorage-fallback behavior.
