On this page

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

Browser SDK 2 reference

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. To find the release that added or changed a feature, go to 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() 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:

For every code and message, go to 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>

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.

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>
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

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();

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();

Plugin

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

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 and Custom enrichment. For more, go to SDK plugins.

Types

amplitude.Types exports TypeScript types and constants, including:

Integration exports

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

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

The SDK writes these cookies:

Data collection

Delivery

Transport options

Remote configuration and diagnostics

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.

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.

AttributionOptions

PageTrackingOptions

FormInteractionsOptions

ElementInteractionsOptions

FrustrationInteractionsOptions

NetworkTrackingOptions

Each NetworkCaptureRule accepts:

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

WebVitalsOptions

PerformanceTrackingOptions

Was this helpful?