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

# Web SDK

> Reference for the ManaLens Web SDK: configuration options, snippet attributes, page views and client routing, custom events, identify, consent and campaign capture.

The Web SDK is a JavaScript library under the MIT license. It tracks page views, custom events and identified users, and captures UTM parameters, referrers, referral codes and ad click IDs. See [Install](https://docs.manalens.dev/install.md) to add it to your site.

> [!NOTE]
>
> **Early access.** The Web SDK is available on request during early access: you get the browser bundle (`snippet.global.js`) and a local package archive. The repository is private until launch. To ask for it, use the Contact page of the ManaLens website (`/contact`). The source will be published at launch.

## Configuration

```ts theme={null}
import { createAnalytics } from '@untitled-analytics/web';

const analytics = createAnalytics({
  publishableKey: 'YOUR_PUBLISHABLE_KEY',
  endpoint: 'https://YOUR_COLLECTOR_ENDPOINT',
});
```

| Option | Type | Default | Description |
| - | - | - | - |
| `publishableKey` | `string` | Required | The [publishable key](https://docs.manalens.dev/api/authentication.md#publishable-key) of one project (`ua_pk_...`). A secret key or an API key throws an error. `writeKey` is its old name and still works. |
| `endpoint` | `string` | Required | The collector base URL, or your [proxy](https://docs.manalens.dev/guides/reverse-proxy.md) path. The SDK posts to `<endpoint>/v0/events`. |
| `autoPageviews` | `boolean` | `true` | Send page views automatically. See [Single-page apps and client routing](#single-page-apps-and-client-routing). |
| `batchSize` | `number` | `10` | Events per request. See [Batching](#batching). |
| `flushIntervalMs` | `number` | `5000` | Time between sends, in milliseconds |
| `retryCount` | `number` | `3` | Retries after a server error (408, 429, 5xx), from 0 to 10 |
| `maxQueueSize` | `number` | `512000` | Queue limit in bytes, from 200 to 500 KB. The oldest events are dropped first. |
| `crossSubdomainCookies` | `boolean` | `true` | Share the visitor ID across subdomains. See [Cross subdomain tracking](#cross-subdomain-tracking). |
| `requireConsent` | `boolean` | `false` | Start in [consent mode](#consent) |
| `tracking` | `boolean` or object | `true` | `false` turns the SDK off. An object sets [exclusion rules](#excluding-traffic). |
| `tracking.excludeHosts` | `string[]` | `[]` | Hosts where nothing is sent |
| `tracking.excludePaths` | `string[]` | `[]` | Paths where nothing is sent |
| `tracking.excludeTimezones` | `string[]` | `[]` | Visitor timezones that are not tracked |
| `tracking.excludeQueryParams` | `string[]` | `[]` | Query parameters the SDK never reads |
| `disabled` | `boolean` | `false` | Send no events and use no browser storage. The same as `tracking: false`. |
| `logger` | `{ enabled?, levels? }` | Off | Console logs. See [Logging](#logging). |
| `ready` | `(analytics) => void` | None | Called once after the SDK starts. See [Ready callback](#ready-callback). |
| `errorHandler` | `(error) => void` | None | Called when events are dropped after a send. See [Batching](#batching). |
| `app` | object | None | The app context of a browser or Electron game. See [App context](#app-context). |

### Local testing and environments

The SDK tracks every host, **including `localhost`**. This is different from Formo's SDK, which skips localhost by default. Events from `localhost` reach the collector only when the project domain allows them (for example a project with the domain `localhost`).

To send nothing from some environments, use the `tracking` option:

```ts theme={null}
// On or off
createAnalytics({ publishableKey, endpoint, tracking: process.env.NODE_ENV === 'production' });

// Or rules
createAnalytics({ publishableKey, endpoint, tracking: { excludeHosts: ['localhost', 'staging.example.com', '*.vercel.app'] } });
```

`tracking: false` is the same as `disabled: true`: no events and no browser storage.

### Logging

Logging is off by default. Turn it on with `logger`:

```ts theme={null}
createAnalytics({ publishableKey, endpoint, logger: { enabled: true, levels: ['error', 'warn', 'info'] } });
```

Without `levels`, all levels print. The `levels` list is matched exactly: `['warn']` prints warnings only, not errors. With the snippet, `data-debug="true"` prints all levels.

| Level | What the SDK prints |
| - | - |
| `info` | Start (with `autoPageviews` and consent mode), disabled, excluded timezone, opt-out |
| `debug` | Each queued event (type and event name), each sent batch (count), events not sent on an excluded host or path |
| `warn` | A failed send that is retried (HTTP status or network error), a full queue that dropped an event |
| `error` | Events dropped: refused by the collector, or out of retries |
| `trace` | Nothing at the moment |

Logs never contain property values, traits, user IDs or keys.

### Batching

The SDK keeps events in memory (never in browser storage) and sends them in batches: when `batchSize` events wait, every `flushIntervalMs`, when the page hides (with `keepalive`), and at once after `identify()`. `flush()` sends now.

```ts theme={null}
createAnalytics({ publishableKey, endpoint, batchSize: 20, flushIntervalMs: 10_000 });
```

* **Server errors** (408, 429, 5xx): the batch is sent again, at most `retryCount` times. Between attempts, the SDK waits 1 s, 2 s, 4 s and so on up to 30 s, with jitter, or longer when a `429` has `Retry-After` (up to 60 s).
* **Network errors** (offline): the events wait in memory and are not counted as retries.
* **Other 4xx** (for example `401` for a wrong key, or `403` for a page that is not on the project domain): the batch is dropped.
* **Queue limit**: above `maxQueueSize` bytes, the oldest events are dropped.

`errorHandler` gets an error each time events are dropped: refused by the collector, or a server error after `retryCount` retries. The error is a `SendError` with `status` (the HTTP status) and `dropped` (the number of events). Network errors do not call it. A refused batch is dropped and is not sent again. In SDK versions after 0.4.0, the error has `reasons` (the reason codes of the collector, for example `SESSION_ID_REQUIRED`) and the message has the text of the collector.

```ts theme={null}
createAnalytics({ publishableKey, endpoint, errorHandler: error => console.warn('Analytics events dropped', error) });
```

### Ready callback

`ready` runs once, at the end of `createAnalytics()`, with the instance. It runs also when the SDK is disabled. An error in it is caught and logged.

```ts theme={null}
createAnalytics({ publishableKey, endpoint, ready: analytics => analytics.track('app_loaded') });
```

The snippet makes `window.untitledAnalytics`, then dispatches the `untitled-analytics:ready` event on `window` (`event.detail` is the instance). Add the listener before the snippet runs, or check `window.untitledAnalytics` first:

```html theme={null}
<script>
  function onAnalytics(analytics) { analytics.track('app_loaded'); }
  if (window.untitledAnalytics) onAnalytics(window.untitledAnalytics);
  else window.addEventListener('untitled-analytics:ready', function (event) { onAnalytics(event.detail); }, { once: true });
</script>
```

### Excluding traffic

```ts theme={null}
createAnalytics({
  publishableKey,
  endpoint,
  tracking: {
    excludeHosts: ['staging.example.com', '*.vercel.app'],
    excludePaths: ['/admin/*', '/internal'],
    excludeTimezones: ['Europe/London'],
    excludeQueryParams: ['ref'],
  },
});
```

| Rule | Match | Effect |
| - | - | - |
| `excludeHosts` | An exact host, or `*.` for every subdomain (`*.vercel.app` does not match `vercel.app`). Case-insensitive. | No event is sent and no identity cookie is written on that host. |
| `excludePaths` | An exact path, or a prefix that ends in `/*` (`/admin/*` matches `/admin` and every path under it) | No event is sent on that path. Checked for each event, so a single-page app that leaves the path sends again. |
| `excludeTimezones` | IANA names (`Europe/London`), case-insensitive, also renamed zones (`Asia/Kolkata` and `Asia/Calcutta`) | The visitor is not tracked at all: no events, no browser storage, and an existing identity is deleted. Best effort: a visitor can change the timezone. |
| `excludeQueryParams` | Query parameter names, case-insensitive | The SDK never reads these parameters. |

The SDK never sends a full query string or a fragment: page URLs are origin and path, and the referrer is an origin. It reads only the [campaign parameters](#referrals-and-campaign-capture). Use `excludeQueryParams` to keep one of them out of every event, for example `['ref']`.

An `identify()` on an excluded page is held and sent with the first event on an allowed page. A campaign from an excluded landing page is not carried.

### Consent

Consent mode is off by default: the SDK stores a persistent visitor ID at once. Sites that need consent before analytics storage set `requireConsent: true` (snippet: `data-require-consent="true"`). Then, until `setConsent(true)`:

* the SDK reads and writes no cookies or localStorage;
* page and track events are sent without `anonymous_id`, `session_id` and `user_id`;
* an `identify()` call is held in memory and sent when consent is granted.

`setConsent(false)` clears all identity storage and removes identity from queued events. `optOut()` drops queued events, clears identity and stores an opt-out flag for one year. `optIn()` removes the flag. See [Consent](https://docs.manalens.dev/guides/consent.md).

### Cross subdomain tracking

| Value | Behavior |
| - | - |
| `true` (default) | Identity cookies are set on the apex domain (`.example.com`), so `example.com` and `play.example.com` share one visitor ID. An existing host-only cookie moves to the apex domain. Public suffixes such as `vercel.app` stay host-only. |
| `false` | Cookies are on the current host only. Snippet: `data-cross-subdomain="false"`. |

With apex cookies, every subdomain can read the IDs. Use `false` if you host untrusted content on a subdomain.

### Referrals and campaign capture

From the landing URL, the SDK reads only these query parameters:

* **UTM**: `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`, `utm_id`, `utm_source_platform`, `utm_creative_format`, `utm_marketing_tactic`
* **Referral code**: `ref`, or `referral` or `referral_code` (sent as `ref`)
* **Ad click IDs**: Google `gclid`, `gbraid`, `wbraid` and `gad_source`; Meta `fbclid`; Microsoft `msclkid`; TikTok `ttclid`; X `twclid`; LinkedIn `li_fat_id`; Reddit `rdt_cid`; Snapchat `ScCid`

It also sends the referrer origin when it is another site, or the app (`android-app://com.google.android.youtube`) when an Android app opened the link. From the values, it adds `paid_source` (the ad network, or `paid_utm` for a paid `utm_medium`) and `click_id` (the first click ID found). `gad_source` marks Google but is not a click ID. Values that are too long or have unsafe characters are dropped.

The SDK keeps the campaign in memory across route changes and attaches it to later events. A new tagged landing replaces it, and it is cleared at UTC midnight. It is not written to browser storage. See [attribution](https://docs.manalens.dev/attribution/overview.md).

### Single-page apps and client routing

`page(properties?)` sends a page view of the current page. **Without properties, it sends nothing when the path and query are the same as the last page view.** With properties, it always sends.

With `autoPageviews: true` (the default), the SDK sends a page view:

| When | What the SDK does |
| - | - |
| First load | Sends one page view at once, with the current title. |
| `history.pushState` / `replaceState` | The SDK wraps both. It waits one tick, so the router can set the new title, then sends a page view only when the **path** changed. A query-only change (filters, tabs) and a same-URL `replaceState` send none. |
| Back and forward (`popstate`) | The URL changes at once, but the framework shows the new page later. The SDK waits until `document.title` changes (checked every 50 ms, at most 1 second), then reads the page fields and sends. It sends nothing when the path and query did not change (for example a hash change). |
| `ua:navigate` on `window` | Sends at once. Dispatch it after your router shows the new page: `window.dispatchEvent(new Event('ua:navigate'))`. |

A page view that waits is sent at once when the page hides (`pagehide`, or the tab goes to the background), so it is not lost.

With `autoPageviews: false` (snippet: `data-auto-pageviews="false"`), the SDK sends no page view by itself, not even on the first load. Call `page()` on each route change, including the first page.

#### Frameworks with client routing

* **Astro View Transitions** (`<ClientRouter />`): add `data-auto-pageviews="false"` to the snippet and call `window.untitledAnalytics.page()` on every `astro:page-load` event. Astro fires it after the first load and after each navigation (links, back and forward), when the new title is in place. Pages without `<ClientRouter />` do not fire `astro:page-load`: send their page view on the window `load` event. See the `with-astro` example in the ManaLens examples repository.
* **Next.js App Router**: set `autoPageviews: false` and call `page()` when `usePathname()` or `useSearchParams()` changes. See the tab below and the `with-next` example in the examples repository.
* **Other routers**: the automatic page views work without code. If your router has a "page loaded" event, you can also use `autoPageviews: false` and call `page()` from that event.

Register the listener one time only. A second `page()` call for the same path and query sends nothing, so a duplicate listener does not count a page twice.

> [tab] Astro
>
> ```astro src/layouts/Base.astro theme={null}
> <script is:inline src="/snippet.global.js"
>   data-publishable-key="YOUR_PUBLISHABLE_KEY"
>   data-endpoint="https://YOUR_COLLECTOR_ENDPOINT"
>   data-auto-pageviews="false"
>   defer></script>
> <script is:inline>
>   document.addEventListener('astro:page-load', function () {
>     if (window.untitledAnalytics) window.untitledAnalytics.page();
>   });
> </script>
> ```
>
> Put both in the `<head>`. The router keeps a head script that is the same on the next page, so the listener is added once.

> [tab] Next.js App Router
>
> ```ts src/lib/analytics.ts theme={null}
> import { createAnalytics } from '@untitled-analytics/web';
>
> let instance: ReturnType<typeof createAnalytics> | undefined;
>
> export function getAnalytics() {
>   if (typeof window === 'undefined') return undefined;
>   return instance ??= createAnalytics({
>     publishableKey: 'YOUR_PUBLISHABLE_KEY',
>     endpoint: 'https://YOUR_COLLECTOR_ENDPOINT',
>     autoPageviews: false,
>   });
> }
> ```
>
> ```tsx src/components/analytics-tracker.tsx theme={null}
> 'use client';
> import { useEffect } from 'react';
> import { usePathname, useSearchParams } from 'next/navigation';
> import { getAnalytics } from '../lib/analytics';
>
> export function AnalyticsTracker() {
>   const pathname = usePathname();
>   const search = useSearchParams().toString();
>   useEffect(() => { getAnalytics()?.page(); }, [pathname, search]);
>   return null;
> }
> ```
>
> Mount it once in the root layout, inside `<Suspense>`:
>
> ```tsx app/layout.tsx theme={null}
> import { Suspense } from 'react';
> import { AnalyticsTracker } from '../components/analytics-tracker';
>
> export default function RootLayout({ children }: { children: React.ReactNode }) {
>   return (
>     <html lang="en">
>       <body>
>         {children}
>         <Suspense fallback={null}><AnalyticsTracker /></Suspense>
>       </body>
>     </html>
>   );
> }
> ```

> [tab] React Router
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { useLocation } from 'react-router-dom';
> import { createAnalytics } from '@untitled-analytics/web';
>
> export const analytics = createAnalytics({
>   publishableKey: 'YOUR_PUBLISHABLE_KEY',
>   endpoint: 'https://YOUR_COLLECTOR_ENDPOINT',
>   autoPageviews: false,
> });
>
> export function AnalyticsTracker() {
>   const location = useLocation();
>   useEffect(() => { analytics.page(); }, [location.pathname, location.search]);
>   return null;
> }
> ```
>
> Render `<AnalyticsTracker />` once inside your router.

### Snippet attributes

The snippet reads its options from `data-` attributes on its `<script>` tag. The instance is `window.untitledAnalytics`.

| Attribute | Option |
| - | - |
| `data-publishable-key` (old name: `data-write-key`) | `publishableKey` (required) |
| `data-endpoint` | `endpoint` (required) |
| `data-auto-pageviews="false"` | `autoPageviews: false` |
| `data-cross-subdomain="false"` | `crossSubdomainCookies: false` |
| `data-require-consent="true"` | `requireConsent: true` |
| `data-debug="true"` | `logger: { enabled: true }` (all levels) |
| `data-app-platform` | `app.platform` |
| `data-app-storefront` | `app.storefront` |
| `data-app-version` | `app.app_version` |
| `data-app-build` | `app.build` |
| `data-app-engine` | `app.engine` |

Other options (`tracking`, `batchSize`, `flushIntervalMs`, `retryCount`, `maxQueueSize`, `ready`, `errorHandler`) need the npm package.

### App context

A game that runs in a browser or in Electron can set the `app` option. Then every event carries `context.app` with `context.page`. The events stay web events, and the App filters and breakdowns (build, version, platform, storefront, engine) work for them. The Game KPIs and Game health dashboard templates count them as game events. Web events need a page URL on your project domain, a subdomain, or a host in the project's [allowed origins](https://docs.manalens.dev/sdks/app-events.md#allowed-origins). So this works on your own domain and in a game portal build once the portal host is in the list (see [Game portals](#game-portals)). See [Browser and Electron games](https://docs.manalens.dev/sdks/app-events.md#browser-and-electron-games).

```ts theme={null}
const analytics = createAnalytics({
  publishableKey: 'YOUR_PUBLISHABLE_KEY',
  endpoint: 'https://YOUR_COLLECTOR_ENDPOINT',
  app: { platform: 'web', storefront: 'other', app_version: '1.4.0', build: '571', engine: 'other' },
});
```

| Field | Required | Values |
| - | - | - |
| `platform` | Yes | `windows`, `macos`, `linux`, `web`, `android`, `ios`, `other` |
| `storefront` | No | `steam`, `itch`, `epic`, `gog`, `app_store`, `play`, `other` |
| `app_version` | No | Up to 32 characters: `A-Z`, `a-z`, `0-9`, space and `. _ + -` |
| `build` | No | Up to 64 characters: `A-Z`, `a-z`, `0-9`, space and `. _ + -` |
| `engine` | No | `godot`, `unity`, `unreal`, `other` |

With the snippet, use the data attributes:

```html theme={null}
<script src="/snippet.global.js"
  data-publishable-key="YOUR_PUBLISHABLE_KEY"
  data-endpoint="https://YOUR_COLLECTOR_ENDPOINT"
  data-app-platform="web"
  data-app-storefront="other"
  data-app-version="1.4.0"
  data-app-build="571"
  data-app-engine="other"
  defer></script>
```

The SDK drops an app object that is not valid and writes one `console.warn`. The device, OS and browser still come from the browser user agent.

### Game portals

A web game on a portal (itch.io HTML5, CrazyGames and similar) runs in an iframe on the portal's own host, for example `html-classic.itch.zone`. The web SDK works there once that host is in **Project settings > Allowed origins**:

1. Open **Project settings > Allowed origins**. A new project already lists `*.itch.zone` (itch.io). For another portal, click its preset (**Add CrazyGames** adds `*.crazygames.com`) or type the host, then **Save allowed origins**.
2. Load the SDK in the game's HTML page as on any site, and set the `app` option (`platform: 'web'`) so the App filters and the game dashboards count the events.
3. Upload the build to the portal. The collector accepts a web event whose page URL is on an allowed host and refuses any other host with `403` (`Page domain does not match project`).

**Attribution limit.** Inside the iframe the SDK sees the portal's game host, not the portal page around it. So the UTM tags and the referrer of the parent page (the itch.io game page and how the player got there) are not visible. At most the SDK sees the parent page origin as its referrer, such as `https://creator.itch.io`. A page on an itch.io game host with no referrer at all is labelled as a referral from `https://itch.io` (`channel_type` Referrers), so it does not show as Direct. For traffic attribution, use the [itch.io integration](https://docs.manalens.dev/integrations/itch.md) for purchases and [short links](https://docs.manalens.dev/features/short-links.md) for the links you post, since a short link records the click and its campaign before the player reaches the portal.

**Portal rules on analytics.** Check the portal's rules before you add any analytics SDK:

* **itch.io:** the HTML5 docs ([itch.io/docs/creators/html5](https://itch.io/docs/creators/html5)) ask that requests to another domain use HTTPS; they set no rule on analytics SDKs.
* **Poki:** external requests are blocked by default. Analytics providers (including an in-house one) are reviewed case by case, Google products such as Google Analytics cannot be approved, and a game that sends data out needs an in-game privacy policy ([external resources policy](https://developers.poki.com/guide/external-resources-policy), [requirements](https://developers.poki.com/guide/requirements-quality)). Poki's docs do not name the host that serves game builds, so there is no preset; ask Poki for it before you add it by hand.
* **CrazyGames:** runs a game on more than one `crazygames.com` origin ([sitelock](https://docs.crazygames.com/resources/html5/sitelock)), so the preset is `*.crazygames.com`. Its docs recommend ByteBrew for advanced analytics and do not forbid other analytics SDKs. A game that collects personal data beyond the CrazyGames SDK events should show a Terms and Conditions or Privacy Policy notice to new players ([requirements](https://docs.crazygames.com/requirements/intro/), [technical requirements](https://docs.crazygames.com/requirements/technical/)).

### Proxy

Ad blockers can drop requests to an analytics host. Serve the script and send events through your own domain, then set `endpoint` (snippet: `data-endpoint`) to your path. See [Reverse proxy](https://docs.manalens.dev/guides/reverse-proxy.md).

## Methods

| Method | Description |
| - | - |
| `page(properties?)` | Track the current page. Without properties, it sends nothing when the path and query are the same as the last page view. |
| `track(event, properties?)` | Track a custom event |
| `identify(userId, traits?)` | Link this browser to a user and set traits |
| `reset()` | Clear the user ID, anonymous ID and session |
| `setConsent(granted)` | Grant or withdraw consent |
| `optOut()`, `optIn()`, `isOptedOut()` | Control the opt-out flag |
| `getUserId()`, `getAnonymousId()` | Read the current IDs |
| `getSessionId()` | The session ID of the next event, or `undefined` when the SDK sends no identity. SDK versions after 0.4.0. See [Sessions](#sessions). |
| `flush(keepalive?)` | Send queued events now |
| `destroy()` | Clear pending events and listeners |

## Sessions

Each event with an identity has a `session_id`: a UUID that is never the `anonymous_id`. A new session starts after **30 minutes** without an event. In SDK versions after 0.4.0, a new session also starts when the session is **24 hours** old, so a page that stays active for days gets a new session each 24 hours. Before consent, an event has no `anonymous_id` and no `session_id`, and it is in no session.

The collector refuses an event that has an `anonymous_id` and no `session_id`, or a `session_id` equal to the `anonymous_id` (see [the session ID contract](https://docs.manalens.dev/api/events.md#the-session-id-contract)). The SDK always sends a correct pair, so this refusal shows a modified or broken client.

To put a server event (for example a purchase) in the visitor's session, send `getAnonymousId()` and `getSessionId()` to your backend and put them on the event: see [send the client's session ID](https://docs.manalens.dev/sdks/server.md#session-id-of-the-client). A read of `getSessionId()` does not count as activity.

## Track custom events

```ts theme={null}
analytics.track('signup_completed', { plan: 'pro', seats: 5 });
```

* **Event names:** up to 128 characters. Use one naming style, such as `snake_case`, and keep names stable.
* **Properties:** a flat object of string (up to 1024 characters), number, boolean or `null` values.
* **Revenue:** add a numeric `revenue` property to count it in the [Revenue](https://docs.manalens.dev/features/revenue.md) metric.

Track completed actions, such as `signup_completed` or `purchase`, not every click or keystroke.

## Identify users

```ts theme={null}
await analytics.identify('user_123', { email: 'user@example.com', plan: 'pro' });
// On logout:
analytics.reset();
```

See [Identify users](https://docs.manalens.dev/guides/identify-users.md).

## Players who come from your game

When a game made with the [Godot SDK](https://docs.manalens.dev/sdks/godot.md#open-your-website-from-the-game) opens your website with `link_url()`, the URL has a `ua_hid` parameter. On load, the SDK removes it from the address bar and sends one `identity_handoff` event. Reports then count the browser and the game install as one player. No setup is needed. In consent mode, the event waits for `setConsent(true)`.

## Browser storage

The SDK stores a persistent first-party `anonymous_id`, a `session_id` and, after `identify()`, a `user_id`. See [what we collect](https://docs.manalens.dev/data/what-we-collect.md#browser-storage) for keys and lifetimes.

## Examples and source

The SDK repository (private during early access) has a local example (`pnpm example`) that runs against a local collector. The ManaLens examples repository (private for now) has complete projects: `with-html` (the snippet), `with-astro` (Astro View Transitions), `with-next` (Next.js App Router) and `with-threejs` (a browser game served from your own domain; on itch.io and other portals, send [app events](https://docs.manalens.dev/sdks/app-events.md#web-exports-and-cors) instead).


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