---
title: "Web SDK"
description: "Track events, identify users and gate capture on consent from the browser with @pug-sh/browser - via a bundler or the CDN."
---

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

# Web SDK

`@pug-sh/browser` is the browser SDK for Pug, open-source product analytics. It
captures events from browser apps - React, Vue, Next.js, or
plain JavaScript. It authenticates with your **public key** (`pub_...`), which
is write-scoped (events + identify) and safe to ship in client code, and follows
the [same model as every Pug SDK](/sdks): initialize once, track events,
identify users, reset on sign-out.

## Install

```bash
npm install @pug-sh/browser
# or: pnpm add @pug-sh/browser | yarn add @pug-sh/browser | bun add @pug-sh/browser
```

[View `@pug-sh/browser` on npm](https://www.npmjs.com/package/@pug-sh/browser)

Use it from a **bundler** (Vite, webpack, esbuild, Next.js, ...) as below, or
with no build step from the **CDN**, through the
[loader snippet](#loader-snippet) or a [one-tag install](#one-tag-install). Both
expose the same API.

Import named exports from the package root, and call `init()` once wherever your
app boots. There are no framework-specific packages.

```ts
import { init, track, identify, reset } from '@pug-sh/browser'
```

Verify by opening your dashboard's **Live** view - an auto-tracked `page_view`
appears within ~15 seconds.

Working with a coding agent? Paste this instead - it points the agent at the
markdown copy of this page. More in [Install with AI](/get-started/ai-setup).

```text
Add Pug product analytics to this app.

Read these first - they are the current source of truth, and more recent than your training data:
- https://docs.pug.sh/sdks/web/index.md - SDK reference
- https://docs.pug.sh/get-started/index.md - quickstart
- https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog

Then read this codebase before you write anything, and work out what the product actually does: its routes or screens, its main models, and the handful of things a user comes here to complete. The events worth tracking are the moments the product exists to produce - an account created, an order placed, a document shared - not every button on the page. If you cannot state the core action in one sentence, keep reading.

Then:
1. Install @pug-sh/browser.
2. Call init() exactly once, where the app boots, in the browser only - never during SSR. In the Next.js App Router that means a "use client" provider mounted from the root layout.
3. Read the project ID and public key from environment variables. The public key starts with pub_ and is safe to ship. A private key starts with prv_ and must never reach client code.
4. Leave auto-tracking on and do not hand-roll page views - init() already captures them.
5. Add track() calls for the three or four actions you identified - the ones someone would look at in a weekly review. Property values must be plain JSON scalars: strings, numbers, booleans, dates.
6. If this app has authentication, call identify() after sign-in and reset() on sign-out. Note that the SDK is cookieless until optInTracking() is called, so identify() is a no-op without granted consent - tell me whether I need a consent banner rather than opting users in silently.

Name events from the catalog before you invent one. It holds 127 well-known events across 19 families - commerce, authentication, billing, media, forms, support, workspace and more - and a well-known name is type-checked as you write it and fills in dashboards that a custom name leaves empty. Search it for every action you are about to track, and take property names and types from that page rather than from whatever reads idiomatically. Fall back to a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not.

Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this product does, then list the files you changed, the event names you chose, and the environment variables I need to set.
```

### Next.js App Router

In the App Router, `init` must run in the browser, not during SSR, so call it
from a client provider:

```tsx title="components/PugProvider.tsx"
'use client'

import { init } from '@pug-sh/browser'
import { useEffect } from 'react'

export function PugProvider({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    init(process.env.NEXT_PUBLIC_PUG_PROJECT_ID!, {
      apiKey: process.env.NEXT_PUBLIC_PUG_PUBLIC_KEY!
    })
  }, [])
  return <>{children}</>
}
```

The App Router also navigates without a full History push, so auto-tracking
fires `page_view` only on the initial load. Track later navigations with
`track('page_view')` in a `usePathname()` effect.

### Loader snippet

**Via CDN (no bundler).** This and the [one-tag install](#one-tag-install) each
load one self-contained file from Pug's CDN (`cdn.pugs.dev`) that puts the full
API on `window.pug` (`pug.track(...)`, `pug.identify(...)`, ...). Use one, not
both. The version is pinned in the URL (`/v0.1.8/`), so bump it when you
upgrade, on every page at once - see [v0.1.0](#v010).

Paste this into `<head>`. It defines `window.pug` immediately and loads the
bundle asynchronously; calls made before it arrives (`init`, `track`, consent
changes) are queued and replayed in order. Call `pug.init()` first - the SDK
drops calls queued ahead of it.

```html
<script>
  !(function (w, d) {
    if (w.pug) { if (!w.pug._q) console.warn('[Pug SDK] window.pug already defined by another script; not loaded.'); return; }
    var q = [];
    var pug = (w.pug = { _q: q, _v: 1 });
    var methods = ('init track identify reset destroy setAutoCapture setTrackingConsent optInTracking ' +
      'optOutTracking isTrackingEnabled getTrackingConsent isConsentPending rotate ready').split(' ');
    methods.forEach(function (m) {
      pug[m] = function () { if (q.length < 1000) q.push([m, [].slice.call(arguments)]); };
    });
    var s = d.createElement('script');
    s.async = true;
    s.src = 'https://cdn.pugs.dev/v0.1.8/pug.min.js';
    s.onerror = function () { console.warn('[Pug SDK] Failed to load ' + s.src); };
    d.head.appendChild(s);
  })(window, document);

  // Always init first - calls queued before init() are dropped by the SDK.
  pug.init('YOUR_PROJECT_ID', { apiKey: 'pub_YOUR_PUBLIC_KEY' });
</script>
```

Queued calls return `undefined` instead of their real value, so put any read or
`await` inside `pug.ready(cb)` (CDN only). It runs at its place in the queue, or
synchronously once the SDK is live:

```html
<script>
  pug.track('signup', { plan: 'pro' })   // queued, replayed in order after load
  pug.ready(function () {
    // Runs once the SDK is live - safe to read state or await here.
    if (pug.getTrackingConsent() === 'granted') pug.identify('user-123', { plan: 'pro' })
  })
</script>
```

### One-tag install

One self-initializing tag with no inline script, for pages whose CSP forbids
inline scripts. It inits from its `data-*` attributes: `data-project-id` and
`data-api-key` are required, `data-endpoint` sets a self-hosted origin, and
`data-options` takes any other [init option](#initialize) as JSON
(`trackingConsent`, `autoCapture`, ...).

```html
<script
  async
  src="https://cdn.pugs.dev/v0.1.8/pug.min.js"
  data-project-id="YOUR_PROJECT_ID"
  data-api-key="pub_YOUR_PUBLIC_KEY"
  data-options='{"trackingConsent":{"initial":"cookieless","persist":true},"maxAgeDays":390}'
></script>
```

JSON can't hold functions, so `beforeSend` isn't available here and
[`redactUrlParams`](#redacting-pii), on by default, is the only URL masking.
There's no pre-load queue either: `window.pug` exists only once the bundle
loads, so call `pug.*` from code that runs later, or use the loader snippet.

Attributes are validated at runtime and **fail closed**: a missing
`data-project-id` or `data-api-key`, or unparseable `data-options`, aborts the
init, and an unrecognized `trackingConsent` value resolves to `'denied'`.

## Initialize

Call `init` **once** at startup with your project ID and public key - every
other call needs it first. Find your project ID in the dashboard URL
(`/p/<projectId>`), and your public key on your project **Overview** or under
**Settings > API Keys**.

```ts
import { init } from '@pug-sh/browser'

init('YOUR_PROJECT_ID', {
  apiKey: 'pub_YOUR_PUBLIC_KEY'
})
```

`init` returns nothing. It **throws** if `projectId` or `apiKey` is missing, and
no-ops (with a console warning) if called a second time or outside a browser.

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | `string` | **required** | Public key (`pub_...`), sent as `x-api-key`. |
| `endpoint` | `string` | `https://api.pugs.dev` | API base URL; set it only when self-hosting. A non-`https` origin other than localhost warns at init. |
| `batch` | `BatchOptions` | `maxSize 10`, `maxWaitMs 5000`, `maxQueueSize 1000` | Queue size and flush timing. |
| `session` | `SessionConfig` | `idleTimeoutMinutes 30`, `maxSessionMinutes 1440` | Session idle and max-duration timeouts (minutes). |
| `autoCapture` | `boolean \| AutoCaptureSelection` | `true` | `true` enables every tracker, `false` none, an object is an allowlist. See [Auto-tracking](#auto-tracking). |
| `trackingConsent` | `TrackingConsent \| TrackingConsentConfig` | `'cookieless'` | Consent gate. See [Tracking consent](#tracking-consent). |
| `crossSubdomainTracking` | `boolean \| { domain }` | `false` | Share identity across subdomains through a first-party cookie, once consent is `'granted'`. See [Cross-subdomain identity](#cross-subdomain-identity). |
| `maxAgeDays` | `number` | `365` | How long stored identifiers live, counted from first write. See [Retention](#retention). |
| `redactUrlParams` | `readonly string[] \| false` | built-in list | Query/fragment params whose values are replaced with `redacted` in `$url`, `$referrer` and form actions. See [Redacting PII](#redacting-pii). |
| `beforeSend` | `BeforeSendFn` | - | Redact, rewrite or drop each event before it is sent. Fails closed. See [Redacting PII](#redacting-pii). |
| `debug` | `boolean` | `false` | Log internal activity to `console.debug` (DevTools' "Verbose" level). Warnings and errors are logged regardless. |
| `dryRun` | `boolean` | `false` | Build events as normal but never send them. Doesn't change consent, or what `isTrackingEnabled()` reports. |
| `excludeAutomatedBrowsers` | `boolean` | `false` | Send nothing from automation-driven browsers (Playwright, Puppeteer, Selenium, headless Chrome). See [Automated browsers](#automated-browsers). |

`destroy()` tears the SDK down - it flushes the queue and removes listeners - so
`init()` can run again.

## Track events

The first argument is the event **name** (its `kind`). Any name works without a
schema; [well-known events](/reference/well-known-events) add typed properties
and richer dashboards. A name may hold only ASCII letters, digits, `_`, `.` and
`-`: the server rejects any batch containing another, and the SDK logs an error
and drops that whole batch.

```ts
import { track } from '@pug-sh/browser'

// Custom event - any name
track('button_clicked', { label: 'Sign up', page: '/pricing' })

// Well-known event - typed properties
track('purchase', { productId: 'sku_123', amount: 29.99, currency: 'USD' })
```

`track()` **never throws** and returns nothing; events are queued and flushed in
the background.

**Property values** accept `string` (truncated to **1024 bytes** client-side),
`number`, `boolean`, and `Date` (stored as a timestamp). Objects and arrays are
JSON-encoded to a string. `null`, `undefined`, and non-finite numbers are
dropped. Send numbers as numbers - aggregations like Sum don't work on strings.

`track(event, props?, options?)` options:

| Option | Type | Description |
|--------|------|-------------|
| `immediate` | `boolean` | Bypass the batch queue and send right away. |
| `timestamp` | `number` | Override the event time, as **epoch milliseconds** (e.g. `Date.now()`). |

```ts
// Conversion that must arrive before a redirect
track('purchase', { productId: 'sku_789', amount: 99, currency: 'USD' }, { immediate: true })
```

## Identify and sessions

Events accumulate against an anonymous ID until you `identify()` the user on
sign-in, which merges that history into a known profile; call `reset()` on
sign-out. Use a **stable, unique** external ID - your database user ID, not an
email, which can change. Only the **first** identify after an anonymous session
merges prior activity; the same external ID always resolves to the same profile,
and traits are merged server-side, never removed.

```ts
// On sign-in - merge anonymous history into the known profile
await identify('user-123', { email: 'user@example.com', plan: 'pro' })

// On sign-out - clear identity, start a fresh anonymous session
reset()

// New session ID without clearing identity
rotate()
```

`identify(externalId, traits?)` returns a **promise** and **never throws**:
invalid input, a call before `init()`, denied consent, cookieless mode, `dryRun`
and RPC failures are logged, and the promise resolves without sending. The
`externalId` must not start with `cookieless-`, a prefix the server reserves for
identities it derives; it rejects any batch carrying one.

`reset()` clears the stored identity and starts a new anonymous session; it does
**not** delete the profile. It sends any queued events first, and **returns
`false`** when something couldn't be removed - with
[cross-subdomain identity](#cross-subdomain-identity), that means the cookie
survived on the registrable domain and the next person on that machine inherits
it.

```ts
if (!reset()) {
  showSignOutWarning()
}
```

| Function | Clears identity | New device ID | New session ID |
|----------|-----------------|---------------|----------------|
| `rotate()` | No | No | Yes |
| `reset()` | Yes | Yes | Yes |

> **Identify needs a stored identifier**
>
> Under the default `'cookieless'` consent state there's no stored anonymous ID to
> merge, so `identify()` is a no-op (warned once per page load) until the reader
> grants consent - see [Tracking consent](#tracking-consent). To branch on that,
> check `getTrackingConsent() === 'granted'`; `isTrackingEnabled()` is also `true`
> when cookieless.

### Sessions

Sessions group events within a single visit, ending at the idle or max-duration
timeout:

1. **First event** (session ID created)
2. **Events within timeout** (same session ID)
3. **Idle past timeout** (session expires)
4. **Next event** (new session ID (identity kept))

The session is shared across tabs through `localStorage`; set the timeouts with
the `session` [init option](#initialize).

Under the default `'cookieless'` consent state, though, the SDK stores no
session and sends no `sessionId`: the server derives one from the daily-rotating
anonymous ID and closes it after 30 minutes of inactivity. The `session`
timeouts apply once consent is granted.

### Cross-subdomain identity

Identity is stored in origin-scoped `localStorage` by default, so
`www.example.com` and `app.example.com` see two unrelated visitors.
`crossSubdomainTracking` moves it to a first-party cookie on the registrable
domain, making them one profile.

```ts
init('YOUR_PROJECT_ID', {
  apiKey: 'pub_YOUR_PUBLIC_KEY',
  crossSubdomainTracking: true,                 // auto-discover the registrable domain
  // crossSubdomainTracking: { domain: 'example.com' },  // or pin it explicitly
})
```

It shares the anonymous ID, the `identify()`ed external ID, session state and
the persisted consent choice, so an opt-out on one subdomain applies to the
others. **Every subdomain must use the same project**: the cookie is keyed by
project, and a mismatch silently splits each visitor in two.

> **It does nothing until consent is granted**
>
> In the default [cookieless](#tracking-consent) state nothing is written to the
> device, cookie included, so turning this on alone shares nothing until the
> reader opts in. If sharing isn't happening, check `getTrackingConsent()` before
> your domain.

A banner-free pattern for a marketing site and an app on one domain: the **app**
grants consent at sign-in and drops back to cookieless on sign-out, and the
**marketing site** grants only when the shared cookie already exists, staying
cookieless otherwise. Returning customers land on their profile and anonymous
readers are still counted, but pre-signup visits never join the profile, since a
cookieless visitor has no anonymous ID to merge.

Before switching it on:

- **It relaxes browser isolation** from same-origin to same-site.
- **On a multi-tenant domain not on the
  [Public Suffix List](https://publicsuffix.org/)** (`a.myplatform.com` and
  `b.myplatform.com` as separate customers), auto-discovery picks the shared
  `myplatform.com`, letting tenants read each other's identity. Pin an explicit
  `{ domain }` there.
- **It falls back** to a host-only cookie on `localhost` and IP hosts, and to
  `localStorage` when cookies are blocked. Cookies set over HTTPS carry
  `Secure`, so only HTTPS subdomains share identity.
- **Sessions end on timeout only**: the usual rotation once every tab is closed
  is disabled.

## Auto-tracking

Six trackers run by default, with no `track()` calls needed. Every auto-tracked
event also carries the standard [auto-properties](/reference/auto-properties),
and the server attaches enrichment properties to every event. Auto-property keys
are camelCase (`$utmSource`, `$pageTitle`, `$screenWidth`) except the
server-set `$bot_reason`, `$bot_score` and `$verified_bot`.

Pass an allowlist to run only some, and change it at runtime with
`setAutoCapture()`:

```ts
import { init } from '@pug-sh/browser'

init('YOUR_PROJECT_ID', {
  apiKey: 'pub_YOUR_PUBLIC_KEY',
  autoCapture: { pageView: true, click: true }
})
```

Omitted keys stay off, and `false` never turns anything on: the object above
enables page views and clicks only, and `{ scroll: false }` enables nothing at
all. TypeScript accepts only `true` as a value, so for a flag known at runtime,
omit the key with `|| undefined`:

```ts
autoCapture: { pageView: true, scroll: enableScroll || undefined }
```

Plain JavaScript and the [one-tag install](#one-tag-install) aren't
type-checked, so the SDK warns at runtime instead: on an explicit `false`, an
unknown key, a non-boolean value, or a selection that enables nothing.

| Tracker | Allowlist key | Event(s) | Captured properties |
|---------|---------------|----------|---------------------|
| Page views | `pageView` | `page_view` | auto-properties only (`$url`, `$referrer`, ...) |
| Clicks | `click` | `click` | `tag`, `id`, `class`, `text` (the element's [own text](#redacting-pii), max 50 chars), `x`, `y` |
| Scroll | `scroll` | `scroll` | `percent` (0-100), `scrollY` |
| Forms | `form` | `form_start`, `form_submit` | form **metadata** only - `formId`, `formName` (both), plus `action` on `form_submit`. Never field values |
| Rage clicks | `rageClick` | `rage_click` | `clickCount`, `element`, `x`, `y` |
| Dead clicks | `deadClick` | `dead_click` | `element`, `text` (the element's [own text](#redacting-pii), max 20 chars), `x`, `y` |

`page_view` fires on the initial load and on History API navigation
(`pushState`, `replaceState`, `popstate`), so call `init()` **before** your
router mounts. The [Next.js App Router](#nextjs-app-router) needs manual
`page_view`s.

`$pageTitle` is sent on `page_view` only, not every event; other events join to
it through `sessionId`.

## Consent and privacy

The Web SDK ships GDPR/CCPA controls that run **in the browser before anything
is sent**, so raw values never leave the device.

### Tracking consent

Consent has three states:

| State | Events sent | Identifier stored on the device |
|-------|-------------|--------------------------------|
| `'granted'` | Yes | Yes - anonymous ID, session, any `identify()`ed external ID |
| `'cookieless'` | Yes | **No** |
| `'denied'` | No | No |

**`'cookieless'` is the default**: events are counted from the first one, but
nothing is written to the device until the reader answers your banner. Pass
`'granted'` for full identity from the first event, or `'denied'` to capture
nothing.

```ts
import { init, optInTracking, optOutTracking, isConsentPending } from '@pug-sh/browser'

init('YOUR_PROJECT_ID', {
  apiKey: 'pub_YOUR_PUBLIC_KEY',
  trackingConsent: {
    initial: 'cookieless',  // default - events flow, nothing is stored
    onReject: 'denied',     // what optOutTracking() resolves to
    persist: true,          // remember the choice across reloads
    respectGpc: true,       // honor the browser's Global Privacy Control signal
  }
})

// Show your banner only while the reader hasn't chosen.
if (isConsentPending()) showCookieBanner()

optInTracking()   // accepted -> 'granted': attach listeners, start storing identity
optOutTracking()  // declined -> resolves to `onReject`
```

`TrackingConsentConfig`:

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `initial` | `'granted' \| 'denied' \| 'cookieless'` | `'cookieless'` | Used until a choice has been persisted. |
| `onReject` | `'denied' \| 'cookieless'` | `'denied'` | What `optOutTracking()` resolves to. `'cookieless'` keeps identity-free counts after a rejection. |
| `persist` | `boolean` | `false` | Store the choice and restore it on the next `init()`. Without it, consent lives in memory and starts from `initial` on every load. |
| `respectGpc` | `boolean` | `false` | Resolve the browser's [Global Privacy Control](#global-privacy-control) signal to `onReject`. Read once per `init()`; a choice made on your site outranks it. Pair it with `persist: true`. |

| Function | Returns | Description |
|---|---|---|
| `optInTracking()` | `boolean` | Grant consent, attach listeners (applying the stored `autoCapture` selection), allow `track()` / `identify()`. |
| `optOutTracking()` | `boolean` | Revoke consent, resolving to `onReject`: clears the stored anonymous ID / session and stops `identify()`. Resolving to `'denied'` also removes listeners and drops `track()`. |
| `setTrackingConsent(state)` | `boolean` | Set any of the three states. `'denied'` means denied, whatever `onReject` says. |
| `isTrackingEnabled()` | `boolean` | Whether events are flowing right now: `true` for both `'granted'` and `'cookieless'`. Independent of `dryRun`. |
| `getTrackingConsent()` | `TrackingConsent \| undefined` | The state the SDK is acting on, or `undefined` before `init()`, which is when a persisted choice is read. |
| `isConsentPending()` | `boolean` | `true` until the reader chooses. Gate your banner on this: `getTrackingConsent()` can't tell a seeded `'granted'` from a chosen one. |
| `setAutoCapture(selection)` | `void` | Change the auto-capture allowlist at runtime: applied immediately while tracking is active, deferred until opt-in when denied. |

#### Cookieless mode

In `'cookieless'` the SDK stores no session, anonymous ID or cross-subdomain
cookie, not even queued event payloads, and sends no identity. The server
derives an anonymous ID instead - an HMAC-SHA256 of the project, IP and user
agent, keyed by a salt that rotates daily and is deleted within 48 hours. IP and
user agent are hash inputs only, never stored or returned. These visitors count
toward traffic but not toward user counts.

Events otherwise carry the same [auto-properties](/reference/auto-properties).
`identify()` is disabled, and granting consent later starts a **fresh**
identity: pre-consent events are never linked to it. The only thing stored is
the consent choice itself, under `persist: true`.

Set both `initial` and `onReject` to `'cookieless'` to count identity-free
traffic before the reader answers and after they decline, behind a plain
accept/reject banner:

```ts
init('YOUR_PROJECT_ID', {
  apiKey: 'pub_YOUR_PUBLIC_KEY',
  trackingConsent: { initial: 'cookieless', onReject: 'cookieless', persist: true }
})
```

For a CMP that separates "reject analytics cookies" from "reject everything",
set the three states directly:

```ts
onAcceptAll(() => setTrackingConsent('granted'))
onRejectAnalyticsCookies(() => setTrackingConsent('cookieless'))
onRejectAll(() => setTrackingConsent('denied'))
```

> **Cookieless is not automatically consent-exempt**
>
> The SDK still reads device characteristics (screen dimensions, locale, client
> hints), which EDPB Guidelines 2/2023 bring within ePrivacy Art. 5(3), and the
> server still processes IP and user agent. Whether that needs consent where you
> operate is yours to decide as the controller.

#### Withdrawing consent

Leaving `'granted'` deletes the stored identity (profile, session, tab registry,
cross-subdomain cookie) and **drops queued events unsent** - unlike `reset()`,
which sends them first.

#### Global Privacy Control

[GPC](https://globalprivacycontrol.org/) is a browser "do not sell or share my
data" signal, legally binding under CCPA/CPRA, sent by Brave (by default),
Firefox, DuckDuckGo and several privacy extensions. With `respectGpc: true`, a
visitor sending it starts at your `onReject` state, no banner needed.

Precedence, lowest first: `initial`, then GPC, then a choice made on your site,
whether stored or a later `optInTracking()`.

Pair it with `persist: true`. Without it, GPC re-resolves on every load,
`isConsentPending()` stays `false` so your banner never shows, and an
`optInTracking()` lasts only for the page, leaving a GPC visitor no way to
accept. The SDK warns when it resolves consent from GPC with persistence off.

#### Retention

`maxAgeDays` (default 365) bounds every identifier the SDK stores: anonymous ID,
external ID, session state and the persisted consent choice. The deadline is
**absolute** - set at first write, never extended by later visits - as CNIL's
13-month rule requires (`maxAgeDays: 390`). Lowering it also shortens existing
deadlines, at their next write.

When the consent record lapses, `isConsentPending()` turns `true` again and your
banner reappears.

Browsers cap it further: Chromium limits any cookie to 400 days, and Safari's
ITP limits script-written cookies far more. And the stored choice is a
preference cache, not proof of consent - to *demonstrate* consent under GDPR
Art. 7(1), record it in your CMP or on your server, with a timestamp and the
policy version.

#### When a consent change doesn't take

`setTrackingConsent()`, `optInTracking()` and `optOutTracking()` return `false`
when a change didn't fully take effect:

- **Called before `init()`**: nothing is applied. On the CDN install, wrap the
  call in `pug.ready()`.
- **Unrecognized state** (a CMP's `'reject'`, `'opt-out'`, a boolean, `null`):
  consent **fails closed to `'denied'`**. Map your CMP's values explicitly.
- **Not persisted** (`persist: true` with storage full or cookies blocked): it
  applies in memory, but the next load falls back to `initial`, so an opt-out
  can quietly revert.
- **A stored identifier couldn't be removed**, such as the
  [cross-subdomain](#cross-subdomain-identity) cookie on the registrable domain.

```ts
if (!setTrackingConsent(choice)) {
  reportConsentFailure(getTrackingConsent())
}
```

### Redacting PII

Four device-side controls keep PII out of captured events.

**`redactUrlParams`**: query and fragment params whose values are replaced with
`redacted` in `$url`, `$referrer` and a form's `action`. The default list covers
credentials and direct identifiers (`token`, `access_token`, `code`, `email`,
`password`, ...) plus any param ending in `_token`, such as
`reset_password_token`. Pass an array to replace the list (matched
case-insensitively by exact name), or `false` to turn redaction off. An empty
array warns and keeps the default list.

**`beforeSend`**: redact, rewrite or drop each event just before it's sent.
Mutate `autoProperties` and `customProperties` in place, then return the event
(or nothing) to send it, or `null` to drop it. URLs arrive with
`redactUrlParams` already applied.

```ts
import { init } from '@pug-sh/browser'

init('YOUR_PROJECT_ID', {
  apiKey: 'pub_YOUR_PUBLIC_KEY',
  redactUrlParams: ['email', 'invite', 'session_id'],
  beforeSend: (event) => {
    const url = event.autoProperties.$url
    if (typeof url === 'string') {
      // Mask path IDs the param-level redaction can't see.
      event.autoProperties.$url = url.replace(/\/orders\/\d+/, '/orders/:orderId')
    }
    if (event.kind === 'debug_ping') return null   // drop entirely
    return event
  }
})
```

It runs synchronously on every event, so keep it cheap. It **fails closed**: a
throw or malformed return drops the event, and a non-function `beforeSend` drops
every event. `$projectId`, `$platform` and `$sdkVersion` are re-asserted
afterwards, and `sessionId` and `distinctId` aren't exposed. Not available on
the [one-tag install](#one-tag-install).

**Element text**: the click and dead-click trackers capture only the clicked
element's own text nodes, never text nested inside it:

```html
<!-- Click the row: text is "Open", not "Open jane@example.com 4111 1111 1111 1111". -->
<div class="row">
  Open
  <span>jane@example.com</span>
  <span>4111 1111 1111 1111</span>
</div>
```

`<textarea>` and `contenteditable` regions report no text, including clicks on
elements inside them; a `contenteditable="false"` island inside one still
reports its own text.

**`data-pug-no-capture`**: for sensitive text in the clicked element itself. It
blanks captured **text** for that element and everything inside it, while `tag`,
`id`, `class` and coordinates are still sent so the click counts - keep PII out
of `id` and `class` too.

```html
<!-- The click still counts, but "jane@example.com" is never captured. -->
<button data-pug-no-capture>Account: jane@example.com</button>

<!-- On a container, it covers every element inside. -->
<div data-pug-no-capture>
  <span>Card ending 4242</span>
  <button>Pay $49.00</button>
</div>
```

### Automated browsers

Browsers driven by automation - WebDriver/CDP (Playwright, Puppeteer, Selenium)
or headless Chrome - are tracked like any other visitor by default; Pug tags bot
traffic server-side rather than dropping it.

`excludeAutomatedBrowsers: true` sends nothing from them: `init()` warns once
and returns without attaching listeners, writing to storage or opening a
connection. That saves cost rather than improving accuracy, since tagged bot
events are still stored and count toward your event total. Leave it off in any
suite that tests your Pug integration.

Every method then does nothing and logs to `console.debug`, and
`optInTracking()`, `optOutTracking()`, `setTrackingConsent()` and `reset()`
return `false`. `isConsentPending()` still returns `true` and
`getTrackingConsent()` `undefined`, so a consent banner behaves as it does in
production. Identity stored by an earlier visit is left alone, even under a
`trackingConsent: 'denied'` seed that would normally purge it.

Detection checks `navigator.webdriver` and a `HeadlessChrome` token in the user
agent or `navigator.userAgentData.brands`. A signal that throws (a privacy
extension shadowing `navigator`) counts as a real visitor, and a driver that
hides all three is left to Pug's server-side bot signals.

## Upgrading

### v0.1.0

Most of this release changes **runtime** behaviour, so it affects JavaScript and
[one-tag](#one-tag-install) installs as well as TypeScript ones.

- **Consent now defaults to `'cookieless'`, not `'granted'`.** An install that
  doesn't configure `trackingConsent` keeps sending events but no longer writes
  a session, an anonymous ID or a cross-subdomain cookie, and `identify()` is a
  no-op. Pass `trackingConsent: 'granted'` to keep the old behaviour, if you
  have a basis for storing identifiers before any banner is answered.
- **Stored identifiers now expire** after [`maxAgeDays`](#retention), and the
  storage format changed. Values written by an earlier version are **deleted**
  on first read, so existing visitors get a fresh anonymous ID once, and an
  `identify()`ed external ID left by the old build is dropped. A persisted
  consent choice is kept and re-stored with a deadline, so a recorded opt-out
  survives.
- **Sensitive URL params are redacted by default** in `$url`, `$referrer` and a
  form's `action`. Pass [`redactUrlParams: false`](#redacting-pii) for the old
  verbatim behaviour.
- **Queued events are dropped, not sent, on consent withdrawal.** `reset()`
  still sends them first.
- **`click` and `dead_click` `text` is the element's own text**, not its whole
  subtree.
- **`$pageTitle` is sent on `page_view` only**, not on every event.
- **`crossSubdomainTracking.maxAgeDays` moved to the top-level `maxAgeDays`**,
  which bounds `localStorage` too. On a one-tag install, an object with no
  `domain` used to auto-discover the registrable domain and now resolves to
  *off* with a warning - pass `true` to keep sharing identity.
- `init()` warns when `endpoint` is not `https` (localhost aside).

> **Roll every CDN page over together**
>
> Each [CDN](#loader-snippet) page pins its own version, and pages on either side
> of v0.1.0 can't read each other's storage, in **any** consent mode. Same-origin
> pages thrash the anonymous ID back and forth, and an old page reads a stored
> external ID as one raw string, envelope included, and sends it as the
> `distinctId` on every event until the rollout finishes.

**`sanitizeUrl` is removed**, replaced by [`beforeSend`](#redacting-pii), which
reaches every property, not just URLs. TypeScript fails to compile; JavaScript
and one-tag installs only warn, silently losing whatever masking `sanitizeUrl`
added beyond the default param redaction. To port it:

```ts
init('YOUR_PROJECT_ID', {
  apiKey: 'pub_YOUR_PUBLIC_KEY',
  beforeSend: (event) => {
    event.autoProperties.$url = maskUrl(event.autoProperties.$url)
    event.autoProperties.$referrer = maskUrl(event.autoProperties.$referrer)
    const action = event.customProperties.action
    if (event.kind === 'form_submit' && typeof action === 'string') {
      event.customProperties.action = maskUrl(action)
    }
    return event
  }
})
```

Unlike `sanitizeUrl`, the hook passes empty strings through, so guard `maskUrl`
with `if (!url) return url` - otherwise a base-relative masker turns a
referrer-less page view into a self-referral. `customProperties` values keep
whatever type you passed to `track()`, so narrow with `typeof` before treating
one as a string, as above with `form_submit`'s `action`, which `sanitizeUrl`
used to cover.

The rest are **compile-time** breaks for TypeScript consumers only:

| Change | What breaks | Fix |
|---|---|---|
| `autoCapture` values are `true`, not `boolean` | `{ scroll: false }` and any `boolean`-typed value | List only what you want enabled; for a runtime value write `scroll: flag \|\| undefined` |
| `track()` is one signature, not two overloads | A wrong type on a well-known field now errors instead of silently compiling | Correct the property type: the error names it. This also surfaces `sizeBytes`, which is a `bigint`: pass `1024n`, not `1024` |
| `getTrackingConsent()` returns `TrackingConsent \| undefined` | Code assuming a non-optional return under `strictNullChecks` | Handle `undefined`, which means "called before `init()`" |
| `TrackingConsent` has a third member, `'cookieless'` | Exhaustive `switch`es and `Record<TrackingConsent, ...>` maps | Handle `'cookieless'` - events flow without identity |
| `optOutTracking()` applies `trackingConsent.onReject` | Nothing by default (`onReject` defaults to `'denied'`) | Opt in with `onReject: 'cookieless'` to keep identity-free counts after a rejection |
| `crossSubdomainTracking: { maxAgeDays }` | The object arm is `{ domain: string }` only | Move it to the top-level `maxAgeDays` |
| `crossSubdomainTracking` is enabled only by `true` or `{ domain }` | A `data-options` value of `{}`, `"true"`, `"false"` or a number no longer enables it (all four used to; `"false"` **enabled** it) | State the opt-in explicitly |
| `TrackingConsentConfig.default` renamed to `initial` | `trackingConsent: { default: ... }` | Rename the key. A stale `default` now warns and **fails closed to `'denied'`** - including in `data-options` JSON, which no compiler checks |

Source: https://docs.pug.sh/sdks/web/index.mdx
