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

# Browser SDK

> Reference for @biqli/analytics configuration, methods, React exports, and global script API.

`@biqli/analytics` runs only in browsers and accepts only a `biqli_pk_...` publishable key.

```bash theme={null}
npm install @biqli/analytics
```

```ts theme={null}
import {BiqliAnalytics} from '@biqli/analytics';

const biqli = new BiqliAnalytics({
  publishableKey: 'biqli_pk_xxxxxxxxx',
});
```

For a site without a package manager, load `https://biq.li/sdk/dist/auto.global.js` with a `data-publishable-key` attribute. See the [HTML guide](/developers/browser/html).

## Configuration

| Option             | Type                            | Default            | Description                                          |
| :----------------- | :------------------------------ | :----------------- | :--------------------------------------------------- |
| `publishableKey`   | `string`                        | Required           | Workspace browser key beginning with `biqli_pk_`     |
| `apiHost`          | `string`                        | `https://biq.li`   | API host or fixed reverse-proxy base                 |
| `clickId`          | `string`                        | None               | Known initial click ID                               |
| `attributionModel` | `'first-click' \| 'last-click'` | `last-click`       | How a new eligible click replaces stored attribution |
| `cookieOptions`    | `CookieOptions`                 | See below          | First-party attribution cookie configuration         |
| `queryParameters`  | `string[]`                      | `['bq_id']`        | URL parameters checked for attribution               |
| `outboundDomains`  | `string[]`                      | `[]`               | Exact or wildcard destinations to decorate           |
| `manualStart`      | `boolean`                       | `false`            | Delay lifecycle listeners and queue flushing         |
| `consent`          | `boolean`                       | `true`             | Initial consent state                                |
| `requestTimeoutMs` | `number`                        | `10000`            | Request timeout, clamped from 1,000 to 60,000 ms     |
| `clientName`       | `string`                        | `@biqli/analytics` | Diagnostic client header                             |
| `clientVersion`    | `string`                        | SDK version        | Diagnostic version header                            |
| `queue`            | `RetryQueueOptions`             | See below          | Browser retry queue limits                           |
| `fetch`            | `typeof fetch`                  | Browser `fetch`    | Custom Fetch-compatible transport                    |

### Cookie options

| Option          | Default           | Description                         |
| :-------------- | :---------------- | :---------------------------------- |
| `domain`        | Current host only | Optional shared cookie domain       |
| `path`          | `/`               | Cookie path                         |
| `sameSite`      | `lax`             | `strict`, `lax`, or `none`          |
| `expiresInDays` | `90`              | Lifetime clamped from 1 to 365 days |

The SDK writes `bq_id` as a first-party cookie. If the browser rejects that cookie, it uses controlled local-storage fallback where available.

### Retry queue defaults

| Option            | Default     |
| :---------------- | :---------- |
| `maxSize`         | 100 records |
| `maxAgeMs`        | 7 days      |
| `maxAttempts`     | 8           |
| `baseDelayMs`     | 1,000 ms    |
| `maxDelayMs`      | 5 minutes   |
| `flushIntervalMs` | 15 seconds  |

## Instance methods

| Method                | Result                                  | Purpose                                                                    |
| :-------------------- | :-------------------------------------- | :------------------------------------------------------------------------- |
| `start()`             | `this`                                  | Start capture, navigation handlers, and queue flushing                     |
| `stop()`              | `this`                                  | Stop lifecycle handlers without clearing attribution                       |
| `teardown()`          | `void`                                  | Stop this instance                                                         |
| `setConsent(granted)` | `void`                                  | Grant or withdraw consent; withdrawal clears attribution and queued events |
| `hasConsent()`        | `boolean`                               | Return current consent state                                               |
| `getClickId()`        | `string \| null`                        | Read eligible stored attribution                                           |
| `setClickId(clickId)` | `void`                                  | Store a validated click ID using the configured model                      |
| `clearClickId()`      | `void`                                  | Clear cookie, fallback storage, and in-memory attribution                  |
| `decorateUrl(url)`    | `string`                                | Add `bq_id` to an allowed outbound destination                             |
| `trackClick(input)`   | `Promise<ClickResponse \| QueuedEvent>` | Create an optional client click                                            |
| `trackLead(input)`    | `Promise<EventResponse \| QueuedEvent>` | Create a client lead                                                       |
| `trackSale(input)`    | `Promise<SaleResponse \| QueuedEvent>`  | Create a client sale                                                       |
| `flush()`             | `Promise<void>`                         | Attempt delivery of due queued events                                      |

`storeStripeSession()` is available for Biqli's browser-to-Stripe attribution adapter. New custom payment implementations should normally persist `bq_id` in their own backend and send sales with the server SDK.

## Tracking inputs

### Client click

| Field      | Type             | Required | Meaning                                        |
| :--------- | :--------------- | :------- | :--------------------------------------------- |
| `domain`   | `string`         | Yes      | Biqli short-link hostname without a protocol   |
| `key`      | `string`         | Yes      | Short-link alias or generated key              |
| `url`      | `string`         | No       | Current page URL; defaults to `location.href`  |
| `referrer` | `string \| null` | No       | Referring URL; defaults to `document.referrer` |
| `eventId`  | `string`         | No       | Stable identity for an idempotent retry        |

### Shared customer identity

Every lead and sale accepts these fields:

| Field                | Type        | Required | Meaning                                                             |
| :------------------- | :---------- | :------- | :------------------------------------------------------------------ |
| `customerExternalId` | `string`    | Yes      | Stable customer ID from your application                            |
| `customerName`       | `string`    | No       | Display name                                                        |
| `customerEmail`      | `string`    | No       | Valid email address                                                 |
| `customerAvatar`     | `string`    | No       | Avatar URL                                                          |
| `clickId`            | `string`    | No       | Explicit attribution click; otherwise the SDK uses its stored click |
| `metadata`           | JSON object | No       | Non-sensitive business metadata                                     |
| `occurredAt`         | `string`    | No       | ISO 8601 UTC event time ending in `Z`                               |

Lead-specific fields are `eventName` (required), `eventId`, and `eventQuantity` (default `1`).

Sale-specific fields are `amount` (required integer minor units), `currency`, `eventName`, `paymentProcessor`, `invoiceId`, `eventId`, and `leadEventName`.

Use a stable lead `eventId`. For a sale, use stable `paymentProcessor` and `invoiceId` values whenever they exist.

## Results and errors

A successful tracking call returns the created or replayed event, customer, click, link, and `request_id`. During a retryable browser outage it can instead return:

```ts theme={null}
{
  queued: true,
  eventId: 'stable-event-identity',
}
```

Rejected calls throw `BiqliError` with `code`, `status`, `requestId`, `details`, and `retryable` properties. A queued result is not proof that the server has received the event; it means the SDK will retry within its configured queue limits.

## Module helpers

```ts theme={null}
import {
  inject,
  getInjectedInstance,
  teardownInjectedInstance,
} from '@biqli/analytics';
```

`inject()` replaces and tears down the previous injected instance. Use the class directly when your application owns instance lifecycle.

## React exports

```tsx theme={null}
import {BiqliProvider, useBiqli} from '@biqli/analytics/react';
```

The hook exposes the SDK, tracking methods, click ID access, consent control, and URL decoration. It must be called under `BiqliProvider`.

## Global script API

The automatic script exposes:

```text theme={null}
Biqli.init                 Biqli.getInstance
Biqli.trackClick           Biqli.trackLead
Biqli.trackSale            Biqli.getClickId
Biqli.setClickId           Biqli.clearClickId
Biqli.setConsent           Biqli.decorateUrl
Biqli.storeStripeSession   Biqli.teardown
```

See the [browser quickstart](/developers/browser/quickstart), [HTML guide](/developers/browser/html), and [React guide](/developers/browser/react).
