---
title: Browser SDK 2 reference
description: "Every public method, class, plugin hook, and init() option in Amplitude Browser SDK 2, verified against version 2.48.1, with signatures, types, defaults, and examples."
product: analytics
lang: en
last_updated: 2026-10-28
token_estimate: 8970
---
# Browser SDK 2 reference

> For AI agents: a documentation index is available at [/docs/llms.txt](/docs/llms.txt). Append `.md` to any page URL for markdown, or send `Accept: text/markdown`.

This reference documents every public export of `@amplitude/analytics-browser` and every option you can pass to `init()`, verified against version 2.48.1. With the script loader, the same members are available on the global `amplitude` object. For options, go to [Configuration options](#configuration-options). To find the release that added or changed a feature, go to [Browser SDK 2 release notes](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2-release-notes).

```ts
import * as amplitude from "@amplitude/analytics-browser";
```

The top-level functions act on a default instance. Each instance from [`createInstance()`](#createinstance) has the same methods.

## Return values

Methods that do asynchronous work return `AmplitudeReturn<T>`, an object with one property, `promise`. Await `promise`, not the return value itself.

```ts
const result = await amplitude.track("Song Played").promise; // correct
const wrapper = await amplitude.track("Song Played"); // returns { promise }, not a Result
```

Tracking methods resolve to a `Result` after the upload attempt finishes:

| Property | Type | Description |
| --- | --- | --- |
| `event` | `Event` | The event as sent, after every plugin ran. |
| `code` | `number` | The HTTP status code, or `0` when the SDK skipped the event. |
| `message` | `string` | A description of the outcome, such as `Event tracked successfully`. |

For every code and message, go to [Read the upload result](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/verify-events#read-the-upload-result).

Calls made before `init()` completes wait in a queue and run in order afterward. Their promises resolve after `init()` finishes and the upload completes.

## Setup

### init

Initializes the instance. Call it once per instance. Calling it again after it finishes tears down every plugin, including ones you added, and starts over.

```ts
init(apiKey: string, options?: BrowserOptions): AmplitudeReturn<void>
init(apiKey: string, userId?: string, options?: BrowserOptions): AmplitudeReturn<void>
```

| Parameter | Type | Description |
| --- | --- | --- |
| `apiKey` | `string` | Your Amplitude project API key. |
| `userId` | `string` | Optional. User ID for this browser. Same as `options.userId`. |
| `options` | `BrowserOptions` | Optional. Refer to the [Configuration reference](#configuration-options). |

`promise` resolves after the SDK fetches remote configuration, installs plugins, and runs queued calls.

```ts
await amplitude.init("YOUR_API_KEY", "user-12345", {
  serverZone: "EU",
}).promise;
```

### createInstance

Creates an independent instance with its own configuration, identity, queue, and plugins. Use it to send data to more than one project.

```ts
createInstance(): BrowserClient
```

```ts
const secondary = amplitude.createInstance();
secondary.init("OTHER_API_KEY", { instanceName: "secondary" });
```

With the script loader, `amplitude.createInstance(name)` also registers the instance under `name`, so calls made before the SDK loads reach it.

### add

Adds a plugin. `setup()` runs immediately if `init()` already ran on the instance, or during `init()` otherwise. The SDK skips a plugin whose `name` matches one already added, and logs a warning.

```ts
add(plugin: Plugin): AmplitudeReturn<void>
```

```ts
await amplitude.add({
  name: "add-app-section",
  execute: async (event) => {
    event.event_properties = { ...event.event_properties, section: "checkout" };
    return event;
  },
}).promise;
```

For the plugin contract, go to [Plugin](#plugin).

### remove

Removes a plugin by name and calls its `teardown()`.

```ts
remove(pluginName: string): AmplitudeReturn<void>
```

```ts
amplitude.remove("add-app-section");
```

### setTransport

Changes the HTTP API for future uploads.

```ts
setTransport(transport: "fetch" | "xhr" | "beacon" | TransportOptions): void
```

```ts
window.addEventListener("pagehide", () => {
  amplitude.setTransport("beacon");
  amplitude.flush();
});
```

### flush

Uploads every queued event now. A manual flush doesn't retry failed uploads.

```ts
flush(): AmplitudeReturn<void>
```

```ts
await amplitude.flush().promise;
```

## Tracking

### track

Sends a custom event. `logEvent()` is an alias with the same signature.

```ts
track(eventInput: string | BaseEvent, eventProperties?: Record<string, any>, eventOptions?: EventOptions): AmplitudeReturn<Result>
logEvent(eventInput: string | BaseEvent, eventProperties?: Record<string, any>, eventOptions?: EventOptions): AmplitudeReturn<Result>
```

| Parameter | Type | Description |
| --- | --- | --- |
| `eventInput` | `string` | `BaseEvent` | The event name, or a [`BaseEvent`](https://amplitude.github.io/Amplitude-TypeScript/interfaces/_amplitude_analytics_browser.Types.BaseEvent.html) object with `event_type` and any other event fields. |
| `eventProperties` | `Record<string, any>` | Optional. Replaces `event_properties` on the event. |
| `eventOptions` | `EventOptions` | Optional. Event fields that override the instance state for this event only, such as `user_id`, `device_id`, `time`, or `insert_id`. |

```ts
amplitude.track(
  "Song Played",
  { title: "Here Comes the Sun" },
  { time: Date.now() },
);
```

### identify

Sends an `$identify` event that updates user properties. If `eventOptions` includes `user_id` or `device_id`, the SDK also calls `setUserId()` or `setDeviceId()` with it.

```ts
identify(identify: Identify, eventOptions?: EventOptions): AmplitudeReturn<Result>
```

```ts
amplitude.identify(new amplitude.Identify().set("plan", "pro"));
```

### setGroup

Assigns the current user to a group by sending an `$identify` event with `groups` set.

```ts
setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions): AmplitudeReturn<Result>
```

```ts
amplitude.setGroup("company", "Acme Inc");
```

### groupIdentify

Sends a `$groupidentify` event that updates properties of one group. Updates apply only to events from that point onward.

```ts
groupIdentify(groupType: string, groupName: string | string[], identify: Identify, eventOptions?: EventOptions): AmplitudeReturn<Result>
```

```ts
amplitude.groupIdentify(
  "company",
  "Acme Inc",
  new amplitude.Identify().set("seats", 250),
);
```

### revenue

Sends a `revenue_amount` event built from a `Revenue` object.

```ts
revenue(revenue: Revenue, eventOptions?: EventOptions): AmplitudeReturn<Result>
```

```ts
amplitude.revenue(
  new amplitude.Revenue().setProductId("pro-annual").setPrice(99.99),
);
```

### trackVideo

Experimental. Tracks `Video Content Started` and `Video Content Stopped` events from a `<video>` element or a player.js embedded player. Requires Browser SDK 2.39.0 or later.

```ts
trackVideo(amplitude: BrowserClient, video: HTMLVideoElement | EmbeddedVideoPlayer, options?: VideoCaptureOptions): (() => void) | Error
```

| Parameter | Type | Description |
| --- | --- | --- |
| `amplitude` | `BrowserClient` | The instance that sends the events. |
| `video` | `HTMLVideoElement` | `EmbeddedVideoPlayer` | The player to observe. |
| `options.vendor` | `VideoVendor` | Optional. The embedded player vendor. |
| `options.extraEventProperties` | `Record<string, string | number | boolean>` | Optional. Properties added to every video event, alongside a generated `view_session_id`. |

Returns a function that stops tracking, or an `Error` if the SDK couldn't attach.

```ts
const stop = amplitude.trackVideo(amplitude, document.querySelector("video")!);
```

## Identity

### getUserId and setUserId

Read or set the user ID for future events. `setUserId(undefined)` clears it.

```ts
getUserId(): string | undefined
setUserId(userId: string | undefined): void
```

```ts
amplitude.setUserId("user-12345");
```

### getDeviceId and setDeviceId

Read or set the device ID for future events.

```ts
getDeviceId(): string | undefined
setDeviceId(deviceId: string): void
```

```ts
amplitude.setDeviceId("2f9d6a1e-4b7c-4f0e-9a51-0c3e8b7d5a12");
```

### reset

Clears the user ID and generates a new device ID. Use it when a user signs out. It doesn't start a new session.

```ts
reset(): void
```

```ts
amplitude.reset();
```

### getIdentity and setIdentity

Read or update the device ID, user ID, and user properties together. When `setIdentity()` receives `userProperties`, it sends an `$identify` event that sets each key with `$set`. `userProperties` holds only the properties set from this page load. `getIdentity()` requires Browser SDK 2.18.0 or later, and `setIdentity()` requires 2.35.0 or later.

```ts
getIdentity(): { deviceId?: string; userId?: string; userProperties?: Record<string, any> }
setIdentity(identity: { deviceId?: string; userId?: string; userProperties?: Record<string, any> }): void
```

```ts
amplitude.setIdentity({
  userId: "user-12345",
  userProperties: { plan: "pro" },
});
```

## Sessions

### getSessionId and setSessionId

Read the current session ID, or end the current session and start one with the given ID. Pass a Unix timestamp in milliseconds. Opted-out instances store the ID and start the session when opt-out turns off.

```ts
getSessionId(): number | undefined
setSessionId(sessionId: number): void
```

```ts
amplitude.setSessionId(Date.now());
```

### extendSession

Marks the session as active now without sending an event.

```ts
extendSession(): void
```

```ts
amplitude.extendSession();
```

## Privacy

### getOptOut and setOptOut

Read or set opt-out. While opt-out is `true`, the SDK drops every event. The value persists in identity storage. `getOptOut()` requires Browser SDK 2.18.0 or later.

```ts
getOptOut(): boolean | undefined
setOptOut(optOut: boolean): void
```

```ts
amplitude.setOptOut(true);
```

## Identify

`Identify` builds user property or group property operations for `identify()`, `groupIdentify()`, and the `identify` init option. Each method returns the same object, so calls chain. Each property can take only one operation per object. The SDK ignores later operations on the same property, and every operation after `clearAll()`.

```ts
const identify = new amplitude.Identify();
```

| Method | Operation | Description |
| --- | --- | --- |
| `set(property, value)` | `$set` | Sets the value. |
| `setOnce(property, value)` | `$setOnce` | Sets the value if the property has none. |
| `add(property, value: number)` | `$add` | Adds to a numeric value. Ignores non-numbers. |
| `append(property, value)` | `$append` | Appends to a list. |
| `prepend(property, value)` | `$prepend` | Prepends to a list. |
| `postInsert(property, value)` | `$postInsert` | Appends values not already in the list. |
| `preInsert(property, value)` | `$preInsert` | Prepends values not already in the list. |
| `remove(property, value)` | `$remove` | Removes values from a list. |
| `unset(property)` | `$unset` | Removes the property. |
| `clearAll()` | `$clearAll` | Removes every property. You can't undo it. |
| `getUserProperties()` | Not applicable | Returns the operations object, for example `{ $set: { plan: "pro" } }`. |

Values accept strings, numbers, booleans, arrays, or objects of those types.

## Revenue

`Revenue` builds the properties of a `revenue_amount` event. Each setter returns the same object.

```ts
const revenue = new amplitude.Revenue();
```

| Method | Event property | Default | Description |
| --- | --- | --- | --- |
| `setProductId(id: string)` | `$productId` | `""` | Product identifier. |
| `setPrice(price: number)` | `$price` | `0` | Price of one item. Can be negative. |
| `setQuantity(quantity: number)` | `$quantity` | `1` | Number of items. Ignores values of `0` or less. |
| `setRevenue(revenue: number)` | `$revenue` | `undefined` | Total revenue. When unset, Amplitude computes `price * quantity`. |
| `setRevenueType(type: string)` | `$revenueType` | `undefined` | Category, such as `subscription` or `refund`. Required for revenue verification. |
| `setCurrency(code: string)` | `$currency` | `undefined` | ISO 4217 currency code for conversion. |
| `setReceipt(receipt: string)` | `$receipt` | `undefined` | Purchase receipt. |
| `setReceiptSig(signature: string)` | `$receiptSig` | `undefined` | Receipt signature. Required for revenue verification. |
| `setEventProperties(properties: object)` | Merged into event properties | `undefined` | Extra properties. The SDK drops `undefined` values and ignores invalid objects. |
| `getEventProperties()` | Not applicable | Not applicable | Returns the event properties the SDK sends. |

## Plugin

A plugin is an object the SDK runs for every event. Pass it to [`add()`](#add).

| Member | Required | Description |
| --- | --- | --- |
| `name` | No | Unique name. Used by `remove()`. The SDK generates a UUID if you omit it and warns. |
| `type` | No | `"before"`, `"enrichment"` (default), or `"destination"`. |
| `setup(config, client)` | No | Runs once when the plugin installs. Receives the resolved `BrowserConfig` and the instance. |
| `execute(event)` | Destination: yes | Before and enrichment plugins return the event, possibly changed, or `null` to drop it. Destination plugins send the event and return a `Result`. |
| `teardown()` | No | Runs on `remove()` and when `init()` runs again. Remove listeners here. |
| `flush()` | No | Destination plugins only. Runs on `amplitude.flush()`. |
| `onIdentityChanged(identity)` | No | Runs after `setUserId()`, `setDeviceId()`, `setIdentity()`, `reset()`, and `identify()`. Best effort. |
| `onSessionIdChanged(sessionId)` | No | Runs when a new session starts. |
| `onOptOutChanged(optOut)` | No | Runs when `setOptOut()` changes the value. |
| `onReset()` | No | Runs on `reset()`. |

For each event, the SDK runs every before plugin, then every enrichment plugin, then every destination plugin. Plugins of the same type run in the order you added them. Plugins added before `init()` install before the built-in autocapture plugins, so they run first.

```ts
const lowercaseUserId: amplitude.Types.BeforePlugin = {
  name: "lowercase-user-id",
  type: "before",
  execute: async (event) => {
    if (event.user_id) event.user_id = event.user_id.toLowerCase();
    return event;
  },
};

amplitude.add(lowercaseUserId);
```

A destination plugin that forwards events to your own endpoint:

```ts
const forwardToWarehouse = (
  url: string,
): amplitude.Types.DestinationPlugin => ({
  name: "forward-to-warehouse",
  type: "destination",
  execute: async (event) => {
    const response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(event),
    });
    return { event, code: response.status, message: response.statusText };
  },
});

amplitude.add(forwardToWarehouse("https://collect.example.com/events"));
```

Amplitude publishes ready-made plugins, such as [Page URL enrichment](https://amplitude.com/docs/sdks/analytics/browser/page-url-enrichment-plugin) and [Custom enrichment](https://amplitude.com/docs/sdks/analytics/browser/custom-enrichment-plugin). For more, go to [SDK plugins](https://amplitude.com/docs/sdks/sdk-plugins).

## Types

`amplitude.Types` exports TypeScript types and constants, including:

| Export | Description |
| --- | --- |
| `BrowserOptions` | The `init()` options object. |
| `BaseEvent`, `Event`, `EventOptions` | Event shapes. |
| `Result` | The resolved value of tracking promises. |
| `Plugin`, `BeforePlugin`, `EnrichmentPlugin`, `DestinationPlugin` | Plugin shapes. |
| `LogLevel` | Enum: `None`, `Error`, `Warn`, `Verbose`, `Debug`. |
| `OfflineDisabled` | Value for the `offline` option that turns off connectivity detection. |
| `TransportType` | `"fetch"` | `"xhr"` | `"beacon"`. A string type, not an enum. |
| `ServerZoneType` | `"US"` | `"EU"`. |
| `IdentityStorageType` | `"cookie"` | `"localStorage"` | `"sessionStorage"` | `"none"`. |
| `AutocaptureOptions`, `AttributionOptions`, `ElementInteractionsOptions` | Autocapture option shapes. |
| `DEFAULT_CSS_SELECTOR_ALLOWLIST`, `DEFAULT_ACTION_CLICK_ALLOWLIST`, `DEFAULT_DATA_ATTRIBUTE_PREFIX` | Element interaction defaults, for extending the lists. |

## Integration exports

These exports exist for other Amplitude packages. Most apps don't need them.

| Export | Purpose |
| --- | --- |
| `AmplitudeBrowser` | The client class. `@amplitude/unified` builds on it. Use `createInstance()` instead. |
| `runQueuedFunctions` | Replays calls queued by the script loader snippet. |
| `_setDiagnosticsSampleRate` | Internal testing only. Can change without notice. |

## Configuration options

This section lists every option of `BrowserOptions`, the configuration object you pass to `init()`, as of Browser SDK 2.48.1. All options are optional. Options marked deprecated still work.

```ts
amplitude.init(apiKey: string, options?: BrowserOptions);
amplitude.init(apiKey: string, userId?: string, options?: BrowserOptions);
```

### Identity and session

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `userId` | `string` | `undefined` | User ID for all events. Same as the `userId` argument of `init()`. The argument wins if you pass both. |
| `deviceId` | `string` | From URL, cookie, or a new UUID | Device ID for all events. Overrides the `ampDeviceId` URL parameter and the stored value. |
| `sessionId` | `number` | From URL, cookie, or `Date.now()` | Session ID, as a Unix timestamp in milliseconds. Starts this session on load. |
| `sessionTimeout` | `number` | `1800000` (30 minutes) | Inactivity, in milliseconds, after which the next event starts a new session. |
| `optOut` | `boolean` | Stored value, or `false` | When `true`, the SDK drops every event and doesn't start sessions. Persists in identity storage. |
| `identify` | `Identify` | `undefined` | An `Identify` object the SDK sends at the start of every session, before `session_start`. Requires 2.25.0 or later. |
| `identityStorage` | `"cookie"` | `"localStorage"` | `"sessionStorage"` | `"none"` | `"cookie"` | Where the SDK persists device ID, user ID, session state, and opt-out. `"none"` keeps them in memory. |
| `cookieOptions` | `CookieOptions` | Refer to [Cookie options](#cookie-options) | Attributes of the identity and campaign cookies. Applies when `identityStorage` is `"cookie"`. |
| `minIdLength` | `number` | `undefined` (Amplitude enforces `5`) | Minimum accepted length for `user_id` and `device_id`. The SDK sends it as `options.min_id_length` with each upload. |
| `instanceName` | `string` | `"$default_instance"` | Name of this instance. Give each instance from `createInstance()` a distinct name. |

#### Cookie options

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `cookieOptions.domain` | `string` | Highest writable domain, such as `.example.com` | Cookie `Domain` attribute. Set `""` for a host-only cookie. |
| `cookieOptions.expiration` | `number` | `365` | Cookie lifetime in days. |
| `cookieOptions.sameSite` | `"Strict"` | `"Lax"` | `"None"` | `"Lax"` | Cookie `SameSite` attribute. `"None"` requires `secure: true`. |
| `cookieOptions.secure` | `boolean` | `false` | Adds the `Secure` attribute, so the browser sends the cookie only over HTTPS. |
| `cookieOptions.upgrade` | `boolean` | `true` | Reads identity from cookies set by the maintenance JavaScript SDK (`amp_` prefix), then deletes them. |

The SDK writes these cookies:

| Cookie | Contents |
| --- | --- |
| `AMP_<first 10 characters of API key>` | Device ID, user ID, session ID, last event time, last event ID, opt-out, and page counter, as URI-encoded JSON in Base64 |
| `AMP_MKTG_<first 10 characters of API key>` | The last campaign that attribution recorded |
| `AMP_TEST`, `AMP_TLDTEST` | Temporary cookies the SDK writes and deletes during `init()` to test cookie support and find the cookie domain |

### Data collection

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `autocapture` | `boolean` | `AutocaptureOptions` | Default set on | Which events the SDK tracks automatically. Refer to [Autocapture options](#autocapture-options). |
| `defaultTracking` | `boolean` | `DefaultTrackingOptions` | `undefined` | Deprecated. Use `autocapture`. Accepts `attribution`, `fileDownloads`, `formInteractions`, `pageViews`, and `sessions`. Ignored when `autocapture` is set. |
| `trackingOptions.ipAddress` | `boolean` | `true` | Sends `ip: "$remote"`, so Amplitude records the request IP. |
| `trackingOptions.language` | `boolean` | `true` | Sends `language` from `navigator.language`. |
| `trackingOptions.platform` | `boolean` | `true` | Sends `platform: "Web"`. |
| `appVersion` | `string` | `undefined` | Sets `app_version` on every event. |
| `customEnrichment` | `boolean` | `{ enabled?: boolean; body: string }` | `false` | Installs the [Custom Enrichment plugin](https://amplitude.com/docs/sdks/analytics/browser/custom-enrichment-plugin), which runs an enrichment function from your project's remote configuration. Experimental. Requires 2.37.0 or later. |
| `partnerId` | `string` | `undefined` | Sets `partner_id`. For partners who build event ingestion integrations. |
| `plan` | `{ branch?, source?, version?, versionId? }` | `undefined` | Tracking plan metadata attached to events. Set by Ampli. |
| `ingestionMetadata` | `{ sourceName?, sourceVersion? }` | `undefined` | Ingestion source metadata attached to events. Set by Ampli and integrations. |
| `pageCounter` | `number` | Stored value | Starting value for `[Amplitude] Page Counter` in this session. |

### Delivery

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `serverZone` | `"US"` | `"EU"` | `"US"` | Data center for event uploads and remote configuration. |
| `serverUrl` | `string` | Derived from `serverZone` and `useBatch` | Upload endpoint. Overrides `serverZone` and `useBatch` for events. |
| `useBatch` | `boolean` | `false` | Sends to the Batch Event Upload API (`/batch`) instead of HTTP V2 (`/2/httpapi`). |
| `flushIntervalMillis` | `number` | `1000` | Milliseconds between the first queued event and the upload. Also the delay before uploading after the browser comes back online. |
| `flushQueueSize` | `number` | `30` | Maximum events per upload request. A larger queue goes out as several requests, one after another. Reaching this size doesn't trigger an early upload. |
| `flushMaxRetries` | `number` | `5` | Upload attempts per event before the SDK drops it. |
| `transport` | `"fetch"` | `"xhr"` | `"beacon"` | `TransportOptions` | `"fetch"` | HTTP API for uploads. Refer to [Transport options](#transport-options). |
| `enableRequestBodyCompression` | `boolean` | `false` | Gzip-compresses bodies of 2 KB or more for a custom `serverUrl`. Amplitude's own endpoints always use compression when the browser supports it. Requires 2.36.0 or later. [Default changed in 2.42.0](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2-release-notes#2420) for Amplitude's endpoints. |
| `offline` | `boolean` | `OfflineDisabled` | `false` | Managed by the SDK from `navigator.onLine`. Set `amplitude.Types.OfflineDisabled` to turn off connectivity detection. Requires 2.4.0 or later. |
| `storageProvider` | `Storage<Event[]>` | `localStorage` | Storage for the unsent-event queue. Falls back to memory when the provider reports it's unavailable. |

#### Transport options

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `transport.type` | `"fetch"` | `"xhr"` | `"beacon"` | `"fetch"` | HTTP API for uploads. |
| `transport.headers` | `Record<string, string>` | `{}` | Extra request headers. Ignored by `beacon`. Can't replace `Content-Type` or `Accept`. Requires 2.33.0 or later. |
| `transport.enableKeepalive` | `boolean` | `true` | Sets `keepalive` on `fetch` requests with bodies of 16 KB or less, measured after compression. [Default changed in 2.43.0](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2-release-notes#2430). |
| `transport.referrerPolicy` | `ReferrerPolicy` | Browser default | `fetch` referrer policy for uploads. Requires 2.44.0 or later. |

### Remote configuration and diagnostics

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `remoteConfig.fetchRemoteConfig` | `boolean` | `true` | Fetches autocapture and custom enrichment settings from your project during `init()`. Remote values override local values per feature. |
| `remoteConfig.serverUrl` | `string` | Amplitude endpoint for `serverZone` | Custom URL for the remote configuration request, such as a proxy. Requires 2.28.0 or later. |
| `fetchRemoteConfig` | `boolean` | `true` | Deprecated. Use `remoteConfig.fetchRemoteConfig`. `false` in either place turns off the fetch, unless `remoteConfig.fetchRemoteConfig` is `true`. Requires 2.10.0 or later. [Default changed in 2.16.1](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2-release-notes#2161). |
| `enableDiagnostics` | `boolean` | `true` | Lets the SDK report its own errors and dropped-event counts to Amplitude. Amplitude sets the sample rate remotely. Diagnostics include event names, error messages, and the user agent, not event properties. |
| `logLevel` | `LogLevel` | `LogLevel.Warn` | Console log level: `None` (0), `Error` (1), `Warn` (2), `Verbose` (3), `Debug` (4). |
| `loggerProvider` | `ILogger` | Console logger | Custom logger with `enable(level)`, `disable()`, `log()`, `warn()`, `error()`, and `debug()` methods. The SDK calls its `enable()` with `logLevel`. |

A custom `loggerProvider` must implement every `ILogger` method. This example forwards SDK errors to your own error reporting and keeps the default console output:

```ts
class ErrorReportingLogger implements amplitude.Types.ILogger {
  private level = amplitude.Types.LogLevel.Warn;
  enable(logLevel: amplitude.Types.LogLevel) {
    this.level = logLevel;
  }
  disable() {
    this.level = amplitude.Types.LogLevel.None;
  }
  log(...args: any[]) {
    if (this.level >= amplitude.Types.LogLevel.Verbose) console.log(...args);
  }
  warn(...args: any[]) {
    if (this.level >= amplitude.Types.LogLevel.Warn) console.warn(...args);
  }
  error(...args: any[]) {
    reportError(args.join(" ")); // Your error reporting, at every log level.
    if (this.level >= amplitude.Types.LogLevel.Error) console.error(...args);
  }
  debug(...args: any[]) {
    if (this.level >= amplitude.Types.LogLevel.Debug) console.log(...args);
  }
}

amplitude.init("YOUR_API_KEY", { loggerProvider: new ErrorReportingLogger() });
```

### Autocapture options

`autocapture` accepts `true`, `false`, or an object with these keys. For behavior and examples, go to [Autocapture](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/usage-guide#autocapture).

| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `attribution` | `boolean` | `AttributionOptions` | `true` | Marketing attribution. |
| `pageViews` | `boolean` | `PageTrackingOptions` | `true` | `[Amplitude] Page Viewed` events. |
| `sessions` | `boolean` | `true` | `session_start` and `session_end` events. |
| `formInteractions` | `boolean` | `FormInteractionsOptions` | `true` | `[Amplitude] Form Started` and `[Amplitude] Form Submitted` events. |
| `fileDownloads` | `boolean` | `true` | `[Amplitude] File Downloaded` events. |
| `pageUrlEnrichment` | `boolean` | `true` | Page and previous-page properties on every event. Experimental. Requires 2.22.0 or later. [Default changed in 2.29.0](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2-release-notes#2290). |
| `elementInteractions` | `boolean` | `ElementInteractionsOptions` | `false` | `[Amplitude] Element Clicked` and `[Amplitude] Element Changed` events. |
| `frustrationInteractions` | `boolean` | `FrustrationInteractionsOptions` | `false` | Rage click, dead click, error click, and thrashed cursor events. Requires 2.24.0 or later. |
| `networkTracking` | `boolean` | `NetworkTrackingOptions` | `false` | `[Amplitude] Network Request` events. Requires 2.17.0 or later. |
| `webVitals` | `boolean` | `WebVitalsOptions` | `false` | `[Amplitude] Web Vitals` events. Experimental. Requires 2.20.0 or later. |
| `performanceTracking` | `boolean` | `PerformanceTrackingOptions` | `false` | `[Amplitude] Main Thread Block` events. Not turned on by `autocapture: true`. Requires 2.41.0 or later. |

`autocapture: true` turns on every key except `performanceTracking`. In a Chrome extension, the default-on keys are off unless you set them. [Default changed in 2.42.1](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2-release-notes#2421).

#### AttributionOptions

| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `trackingMethod` | `"userProperty"` | `"eventProperty"` | an array of both | `["userProperty", "eventProperty"]` | How the SDK records campaigns. Invalid values fall back to the default. `"eventProperty"` requires 2.40.0 or later. [Default changed in 2.45.0](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2-release-notes#2450). |
| `excludeReferrers` | `(string | RegExp)[]` | Your top-level domain, as a RegExp | Referring domains to ignore. Strings match exactly. `userProperty` only. |
| `excludeInternalReferrers` | `boolean` | `{ condition?: "always" | "ifEmptyCampaign" }` | `false` | Ignores referrers on the page's own domain. `true` equals `{ condition: "always" }`. `userProperty` only. Requires 2.36.0 or later. |
| `initialEmptyValue` | `string` | `"EMPTY"` | Value of `initial_*` user properties with no campaign value. `userProperty` only. |
| `resetSessionOnNewCampaign` | `boolean` | `false` | Starts a new session when the campaign changes. `userProperty` only. |
| `fallbackAttributionEvent` | `boolean` | `false` | Sends `[Amplitude] Attribution` on every page view. `eventProperty` only. |

#### PageTrackingOptions

| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `trackOn` | `"attribution"` | `() => boolean` | `undefined` (always) | When to send page views. `"attribution"` sends only with a new campaign. |
| `trackHistoryChanges` | `"all"` | `"pathOnly"` | `undefined` (same as `"all"`) | Which `pushState` and `popstate` URL changes send a page view. |
| `eventType` | `string` | `"[Amplitude] Page Viewed"` | Event name for page views. |

#### FormInteractionsOptions

| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `shouldTrackSubmit` | `(event: SubmitEvent) => boolean` | `undefined` (always) | Return `false` to skip `[Amplitude] Form Submitted` for a submit. Doesn't affect `Form Started`. Requires 2.34.0 or later. |

#### ElementInteractionsOptions

| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `cssSelectorAllowlist` | `string[]` | `DEFAULT_CSS_SELECTOR_ALLOWLIST` | Elements to track. Replaces the default. |
| `actionClickAllowlist` | `string[]` | `["div", "span", "h1", "h2", "h3", "h4", "h5", "h6"]` | Extra elements tracked only when a click changes the DOM or navigates. |
| `pageUrlAllowlist` | `(string | RegExp)[]` | All pages | Pages where tracking runs. |
| `pageUrlExcludelist` | `(string | RegExp | { pattern: string })[]` | None | Pages where tracking never runs. Wins over the allowlist. |
| `shouldTrackEventResolver` | `(actionType: "click" | "change", element: Element) => boolean` | `undefined` | Per-element decision. Overrides every allowlist. |
| `dataAttributePrefix` | `string` | `"data-amp-track-"` | Prefix of `data-` attributes to capture as properties. |
| `maskTextRegex` | `(RegExp | { pattern: string; description: string })[]` | None | Extra patterns to mask in captured text. |
| `visualTaggingOptions` | `{ enabled?: boolean }` | `undefined` | Controls the visual labeling selector integration. |
| `viewportContentUpdated` | `{ enabled?: boolean; exposureDuration?: number }` | `{ enabled: true, exposureDuration: 150 }` | Viewport exposure tracking for zoning. `exposureDuration` is in milliseconds. |
| `shadowDomEnabled` | `boolean` | `false` | Captures interactions in open shadow roots. Experimental. Stays on until the next page load once on. |
| `maxShadowDomDepth` | `number` | `1` | Shadow boundaries to cross, clamped to `1` through `10`. |
| `exposureDuration` | `number` | `150` | Deprecated. Use `viewportContentUpdated.exposureDuration`. |
| `debounceTime` | `number` | Not applicable | Deprecated. Has no effect. |

#### FrustrationInteractionsOptions

| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `rageClicks` | `boolean` | `{ cssSelectorAllowlist?: string[] }` | On, all elements | Four clicks within 50 pixels in one second. |
| `deadClicks` | `boolean` | `{ cssSelectorAllowlist?: string[] }` | On, `DEFAULT_DEAD_CLICK_ALLOWLIST` | Clicks with no DOM or URL change within three seconds. |
| `errorClicks` | `boolean` | `{ cssSelectorAllowlist?: string[] }` | Off. When on: `DEFAULT_ERROR_CLICK_ALLOWLIST` | Clicks followed by an error within two seconds. |
| `thrashedCursor` | `boolean` | `{ directionChanges?: number; threshold?: number }` | Off. When on: `directionChanges: 20` (minimum 5), `threshold: 2000` ms (maximum 4000). | Rapid pointer direction changes. X-axis and Y-axis changes count separately. |
| `pageUrlAllowlist` | `(string | RegExp)[]` | All pages | Pages where tracking runs. |
| `pageUrlExcludelist` | `(string | RegExp)[]` | None | Pages where tracking never runs. |
| `shouldTrackEventResolver` | `(actionType, element) => boolean` | `undefined` | Per-element decision. Overrides the allowlists. |
| `dataAttributePrefix` | `string` | `"data-amp-track-"` | Prefix of `data-` attributes to capture. |
| `maskTextRegex` | `(RegExp | { pattern: string; description: string })[]` | None | Extra patterns to mask. |

#### NetworkTrackingOptions

| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `ignoreAmplitudeRequests` | `boolean` | `true` | Skips requests to Amplitude. |
| `ignoreHosts` | `string[]` | `[]` | Hosts to skip. Supports `*` wildcards. |
| `captureRules` | `NetworkCaptureRule[]` | One rule: all URLs, status `500-599` | Rules checked from last to first. |

Each `NetworkCaptureRule` accepts:

| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `urls` | `(string | RegExp)[]` | All URLs | URLs to match. Supports `*`. Takes precedence over `hosts`. |
| `hosts` | `string[]` | All hosts | Hosts to match. Supports `*`. Use `urls` for new rules. |
| `methods` | `string[]` | All methods | HTTP methods to match. |
| `statusCodeRange` | `string` | `"500-599"` | Comma-separated codes and ranges, such as `"0,400-599"`. |
| `requestHeaders`, `responseHeaders` | `boolean` | `string[]` | `false` | `true` captures a fixed list of non-sensitive headers. An array captures the named headers. |
| `requestBody`, `responseBody` | `{ allowlist?: string[]; excludelist?: string[] }` | Nothing captured | JSON pointers to capture and to remove. `blocklist` is a deprecated alias of `excludelist`. |

Amplitude deprecated `networkTrackingOptions` at the top level of `BrowserOptions`. Use `autocapture.networkTracking`.

#### WebVitalsOptions

| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `reportSoftNav` | `boolean` | `false` | Also reports web vitals for soft navigations in browsers with the Soft Navigations API. Experimental. |

#### PerformanceTrackingOptions

| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `mainThreadBlock` | `boolean` | `{ durationThreshold?: number }` | Off. `performanceTracking: true` turns it on with `durationThreshold: 100`. | Reports main-thread blocks of at least `durationThreshold` milliseconds. |
| `pageUrlAllowlist` | `(string | RegExp)[]` | All pages | Pages where tracking runs. |
| `pageUrlExcludelist` | `(string | RegExp)[]` | None | Pages where tracking never runs. |

