Track events with Browser SDK 2
Browser SDK 2 sends five kinds of data: custom events, user properties, group membership, group properties, and revenue. Each has its own method, and each method returns { promise }, which resolves after the upload attempt. Use these methods for events your tracking plan defines. For page views, clicks, form interactions, and other events the SDK can collect without code, go to Autocapture.
Track a custom event
Pass an event name and, optionally, an object of event properties.
amplitude.track("Song Played", {
title: "Here Comes the Sun",
duration_seconds: 185,
genres: ["rock", "pop"],
});
Use strings, numbers, booleans, arrays, or nested objects as property values. The event name must be a non-empty string. The SDK drops events with an empty name and logs Event skipped due to empty event type.
logEvent() is an alias of track() with the same arguments.
Pass the event as an object
To set more fields than the name and properties, pass a BaseEvent object. This form accepts every field the HTTP V2 API accepts, such as groups, time, app_version, and insert_id.
amplitude.track({
event_type: "Song Played",
event_properties: { title: "Here Comes the Sun" },
time: Date.now() - 60_000,
insert_id: "song-played-8f2c",
});
Set insert_id when the same event might send twice, for example after a retry from your own code. Amplitude ignores a second event with the same insert_id and device_id within seven days.
Override identity for one event
Pass user_id or device_id in the third argument, the event options. The override applies to this event only. Later events still use the identity from setUserId() and setDeviceId().
amplitude.track(
"Invite Sent",
{ channel: "email" },
{
user_id: "user-12345",
},
);
identify() behaves differently. Passing user_id or device_id to identify() also calls setUserId() or setDeviceId(), which changes the identity for every later event.
Wait for an event before navigating
The SDK uploads events in batches about once a second. If your code leaves the page right after track(), wait for the promise first:
await amplitude.track("Checkout Started").promise;
window.location.assign("/checkout");
The default fetch transport already sends with keepalive, so most events survive navigation without waiting. Wait when the event must arrive before the next page loads. For more on unload behavior, go to Send events when the page unloads.
Set user properties
User properties describe the user and stay attached to every later event until they change. Build an Identify object, add one or more operations, and pass it to identify().
const identifyEvent = new amplitude.Identify()
.set("plan", "pro")
.setOnce("first_seen_at", "2026-10-26")
.add("login_count", 1)
.append("visited_sections", "billing");
amplitude.identify(identifyEvent);
The SDK sends an $identify event. It doesn't appear as an event in charts, but it updates the user's properties.
| Method | Effect on the user property |
|---|---|
set(key, value) | Sets the value, replacing any existing value. |
setOnce(key, value) | Sets the value only if the property has no value yet. Use it for first-touch facts, such as a signup date. |
add(key, number) | Adds the number to the current numeric value. Pass a negative number to subtract. A missing property starts at 0. |
append(key, value) | Adds the value, or each item of an array, to the end of a list property. Creates the list if it doesn't exist. |
prepend(key, value) | Adds the value, or each item of an array, to the start of a list property. |
postInsert(key, value) | Like append(), but skips values the list already contains. |
preInsert(key, value) | Like prepend(), but skips values the list already contains. |
remove(key, value) | Removes the value, or each item of an array, from a list property. |
unset(key) | Removes the property from the user. |
clearAll() | Removes every user property. You can't undo it. Ignores every other operation in the same Identify object. |
Each property can appear in only one operation per Identify object. The SDK silently ignores a second operation on the same key, so split conflicting operations across two identify() calls.
To set user properties as part of initialization, so they apply before the first autocaptured event, pass the Identify object to init():
amplitude.init("AMPLITUDE_API_KEY", "user-12345", {
identify: new amplitude.Identify().set("plan", "pro"),
});
The SDK sends this identify each time a new session starts, before the session's start event. The identify option requires Browser SDK 2.25.0 or later.
Assign a user to a group
Groups let you analyze behavior at the account or organization level. Group analytics requires the Accounts add-on.
setGroup() assigns the current user to one or more groups of a type. The assignment persists on the user like a user property.
amplitude.setGroup("company", "Acme Inc");
amplitude.setGroup("team", ["engineering", "design"]);
To associate only one event with a group, without changing the user's groups, set groups on the event:
amplitude.track({
event_type: "Report Exported",
groups: { company: "Acme Inc" },
});
Set group properties
Group properties describe the group, not the user. Use groupIdentify() with an Identify object. All Identify operations work the same way as they do for user properties. Updates apply only to events from that point onward.
const groupProperties = new amplitude.Identify()
.set("plan", "enterprise")
.set("seats", 250);
amplitude.groupIdentify("company", "Acme Inc", groupProperties);
Track revenue
Build a Revenue object and pass it to revenue(). The SDK sends a revenue_amount event that Amplitude uses for revenue analysis.
const purchase = new amplitude.Revenue()
.setProductId("com.example.pro-annual")
.setPrice(99.99)
.setQuantity(2)
.setRevenueType("subscription")
.setCurrency("USD")
.setEventProperties({ coupon: "FALL26" });
amplitude.revenue(purchase);
Amplitude computes revenue as price * quantity unless you call setRevenue(), which sets the total directly. quantity defaults to 1, and setQuantity() ignores values of 0 or less. setPrice() accepts negative values, for example for a refund. Revenue verification requires setRevenueType() and setReceiptSig(). For every setter, go to Revenue in the API reference.
Amplitude converts revenue to your project's currency only when you set currency. For more on currency conversion and revenue event setup, go to Track revenue.
To get the most from revenue data, also track products with the product array method.
Track video playback
trackVideo() sends Video Content Started and Video Content Stopped events from an HTML <video> element or a player.js-compatible embedded player. This API is experimental and can change without notice. Requires Browser SDK 2.39.0 or later.
const video = document.querySelector("video");
if (video) {
const stopTracking = amplitude.trackVideo(amplitude, video, {
extraEventProperties: { placement: "homepage" },
});
// Later, when you no longer need video events:
if (typeof stopTracking === "function") {
stopTracking();
}
}
Every event from one trackVideo() call carries the same view_session_id, a UUID the SDK generates, plus your extraEventProperties. trackVideo() returns an Error instead of a function if it can't attach to the player.
Send events to more than one project
Each Amplitude project has its own API key. To send to two projects, create a second instance with createInstance() and give it a distinct instanceName.
amplitude.init("PRODUCTION_API_KEY");
const marketing = amplitude.createInstance();
marketing.init("MARKETING_API_KEY", {
instanceName: "marketing",
});
amplitude.track("Signup Completed");
marketing.track("Signup Completed");
Each instance keeps its own user ID, device ID, session, queue, and plugins. Instances that share an API key share their identity cookie, so give each project its own key.
Was this helpful?
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.