Browser SDK 2.0
The Browser SDK lets you send events to Amplitude. This library is open-source, check it out on GitHub.
Ampli Wrapper versus the Amplitude SDK
The Ampli Wrapper is an autogenerated library based on your pre-defined tracking plan. This is a lightweight wrapper over the Amplitude SDK that provides type safety, automatic code completion, linting, and schema validation. The generated code replicates the spec in the Tracking Plan and enforces its rules and requirements. This guide is about the Amplitude SDK. To learn more about Ampli Wrapper, see Ampli Wrapper Overview and examples. Click here for more documentation on Ampli for Browser.
Migration guide
This is the documentation for the Amplitude Browser SDK 2.0. If you are using the Browser SDK 1.0, refer to the migration documentation: Browser SDK 2.0 Migration Guide. If you are using the maintenance SDK, refer to the migration documentation: Browser SDK Migration Guide.
SDK bundle size
Search for the package on bundle phobia to view its size and other details.
For example you can search @amplitude/analytics-browser
at a specific version.
Getting started¶
Use this quickstart guide to get started with Amplitude Browser SDK.
Usage¶
Initialize the SDK¶
Important notes about sending events
This SDK uses the HTTP V2 API and follows the same constraints for events. Make sure that all events logged in the SDK have the event_type
field and at least one of device_id
or user_id
, and follows the HTTP API's constraints on each of those fields.
To prevent instrumentation issues, device IDs and user IDs must be strings with a length of 5 characters or more. If an event contains a device ID or user ID that's too short, the ID value is removed from the event. If the event doesn't have a user_id
or device_id
value, the upload may be rejected with a 400 status. Override the default minimum length of 5 characters by passing the min_id_length
option with the request.
You must initialize the SDK before you can instrument any events. Your Amplitude project's API key is required. You can pass an optional user ID and config object in this call. You can use the SDK anywhere after it's initialized anywhere in an application.
// Option 1, initialize with Amplitude API key only
amplitude.init(AMPLITUDE_API_KEY);
// Option 2, initialize with options
amplitude.init(AMPLITUDE_API_KEY, options);
// Option 3, initialize with user ID if it's already known
amplitude.init(AMPLITUDE_API_KEY, 'user@amplitude.com');
// Option 4, initialize with a user ID and options
amplitude.init(AMPLITUDE_API_KEY, 'user@amplitude.com', options);
Configuration¶
Configuration Options
Name |
Description | Default Value |
---|---|---|
instanceName |
string . The instance name. |
$default_instance |
flushIntervalMillis |
number . Sets the interval of uploading events to Amplitude in milliseconds. |
1,000 (1 second) |
flushQueueSize |
number . Sets the maximum number of events that are batched in a single upload attempt. |
30 events |
flushMaxRetries |
number . Sets the maximum number of reties for failed upload attempts. This is only applicable to retryable errors. |
5 times. |
logLevel |
LogLevel.None or LogLevel.Error or LogLevel.Warn or LogLevel.Verbose or LogLevel.Debug . Sets the log level. |
LogLevel.Warn |
loggerProvider |
Logger . Sets a custom loggerProvider class from the Logger to emit log messages to desired destination. |
Amplitude Logger |
minIdLength |
number . Sets the minimum length for the value of user_id and device_id properties. |
5 |
optOut |
boolean . Sets permission to track events. Setting a value of true prevents Amplitude from tracking and uploading events. |
false |
serverUrl |
string . Sets the URL where events are upload to. |
https://api2.amplitude.com/2/httpapi |
serverZone |
EU or US . Sets the Amplitude server zone. Set this to EU for Amplitude projects created in EU data center. |
US |
transportProvider |
Transport . Sets a custom implementation of Transport to use different request API. |
FetchTransport |
useBatch |
boolean . Sets whether to upload events to Batch API instead of instead of the default HTTP V2 API or not. |
false |
appVersion |
string . Sets an app version for events tracked. This can be the version of your application. For example: "1.0.0" |
undefined |
defaultTracking |
boolean | DefaultTrackingOptions . Configures default event tracking |
Check tracking default events |
deviceId |
string . Sets an identifier for the device running your application. |
UUID() |
cookieOptions.domain |
string . Sets the domain property of cookies created. |
undefined |
cookieOptions.expiration |
number . Sets expiration of cookies created in days. |
365 days |
cookieOptions.sameSite |
string . Sets SameSite property of cookies created. |
Lax |
cookieOptions.secure |
boolean . Sets Secure property of cookies created. |
false |
cookieOptions.upgrade |
boolean . Sets upgrading from cookies created by maintenance Browser SDK. If true , new Browser SDK deletes cookies created by maintenance Browser SDK. If false , Browser SDK keeps cookies created by maintenance Browser SDK. |
true |
identityStorage |
string . Sets storage API for user identity. Options include cookie for document.cookie , localStorage for localStorage , or none to opt-out of persisting user identity. |
cookie |
partnerId |
string . Sets partner ID. Amplitude requires the customer who built an event ingestion integration to add the partner identifier to partner_id . |
undefined |
sessionTimeout |
number . Sets the period of inactivity from the last tracked event before a session expires in milliseconds. |
1,800,000 milliseconds (30 minutes) |
storageProvider |
Storage<Event[]> . Sets a custom implementation of Storage<Event[]> to persist unsent events. |
LocalStorage |
userId |
number . Sets an identifier for the user being tracked. Must have a minimum length of 5 characters unless overridden with the min_id_length option. |
undefined |
trackingOptions |
TrackingOptions . Configures tracking of additional properties. Please refer to Optional tracking section for more information. |
Enable all tracking options by default. |
transport |
string . Sets request API to use by name. Options include fetch fro fetch, xhr for XMLHttpRequest , or beacon for navigator.sendBeacon . |
fetch |
Configure batching behavior¶
To support high-performance environments, the SDK sends events in batches. Every event logged by the track
method is queued in memory. Events are flushed in batches in background. You can customize batch behavior with flushQueueSize
and flushIntervalMillis
. By default, the serverUrl will be https://api2.amplitude.com/2/httpapi
. For customers who want to send large batches of data at a time, set useBatch
to true
to set setServerUrl
to batch event upload API https://api2.amplitude.com/batch
. Both the regular mode and the batch mode use the same events upload threshold and flush time intervals.
EU data residency¶
You can configure the server zone when initializing the client for sending data to Amplitude's EU servers. The SDK sends data based on the server zone if it's set.
Note
For EU data residency, the project must be set up inside Amplitude EU. You must initialize the SDK with the API key from Amplitude EU.
amplitude.init(AMPLITUDE_API_KEY, {
serverZone: 'EU',
});
Debugging¶
You can control the level of logs printed to the developer console.
- 'None': Suppresses all log messages.
- 'Error': Shows error messages only.
- 'Warn': Shows error messages and warnings. This is the default value if
logLevel
isn't explicitly specified. - 'Verbose': Shows informative messages.
- 'Debug': Shows error messages, warnings, and informative messages that may be useful for debugging, including the function context information for all SDK public method invocations. This logging mode is only suggested to be used in development phases.
Set the log level by configuring the logLevel
with the level you want.
amplitude.init(AMPLITUDE_API_KEY, {
logLevel: amplitude.Types.LogLevel.Warn,
});
The default logger outputs log to the developer console. You can provide your own logger implementation based on the Logger
interface for any customization purpose. For example, collecting any error messages from the SDK in a production environment.
Set the logger by configuring the loggerProvider
with your own implementation.
amplitude.init(AMPLITUDE_API_KEY, {
loggerProvider: new MyLogger(),
});
Debug Mode¶
Enable the debug mode by setting the logLevel
to "Debug", for example:
amplitude.init(AMPLITUDE_API_KEY, {
logLevel: amplitude.Types.LogLevel.Debug,
});
With the default logger, extra function context information will be output to the developer console when invoking any SDK public method, including:
- 'type': Category of this context, e.g., "invoke public method".
- 'name': Name of invoked function, e.g., "track".
- 'args': Arguments of the invoked function.
- 'stacktrace': Stacktrace of the invoked function.
- 'time': Start and end timestamp of the function invocation.
- 'states': Useful internal states snapshot before and after the function invocation.
Tracking an event¶
Important notes about sending events
This SDK uses the HTTP V2 API and follows the same constraints for events. Make sure that all events logged in the SDK have the event_type
field and at least one of device_id
or user_id
, and follows the HTTP API's constraints on each of those fields.
To prevent instrumentation issues, device IDs and user IDs must be strings with a length of 5 characters or more. If an event contains a device ID or user ID that's too short, the ID value is removed from the event. If the event doesn't have a user_id
or device_id
value, the upload may be rejected with a 400 status. Override the default minimum length of 5 characters by passing the min_id_length
option with the request.
Events represent how users interact with your application. For example, "Button Clicked" may be an action you want to note.
// Track a basic event
amplitude.track('Button Clicked');
// Track events with optional properties
const eventProperties = {
buttonColor: 'primary',
};
amplitude.track('Button Clicked', eventProperties);
You can also pass a BaseEvent
object to the track
function. Refer to the BaseEvent interface for all available fields.
const event_properties = {
buttonColor: 'primary',
};
const event = {
event_type: "Button Clicked",
event_properties,
groups: { 'role': 'engineering' },
group_properties: { 'groupPropertyKey': 'groupPropertyValue' }
};
amplitude.track(event);
Tracking events to multiple projects¶
If you need to log events to multiple Amplitude projects, you'll need to create separate instances for each Amplitude project. Then, pass the instance variables to wherever you want to call Amplitude. Each instance allows for independent apiKeys, userIds, deviceIds, and settings.
const defaultInstance = amplitude.createInstance();
defaultInstance.init(API_KEY_DEFAULT);
const envInstance = amplitude.createInstance();
envInstance.init(API_KEY_ENV, {
instanceName: 'env',
});
Tracking default events¶
Starting version 1.9.1, Browser SDK now tracks default events. Browser SDK can be configured to track the following events automatically:
- Attribution
- Page views
- Sessions
- Form interactions
- File downloads
Tracking default events options
Name |
Value | Description |
---|---|---|
config.defaultTracking.attribution |
Optional. boolean |
Enables/disables marketing attribution tracking. If value is true , Amplitude tracks marketing attribution events otherwise marketing attribution tracking is disabled. Default value is true . |
config.defaultTracking.pageViews |
Optional. boolean |
Enables/disables default page view tracking. If value is true , Amplitude tracks page view events on initialization otherwise page view tracking is disabled. Default value is true .Event properties tracked includes: [Amplitude] Page Domain , [Amplitude] Page Location , [Amplitude] Page Path , [Amplitude] Page Title , [Amplitude] Page URL See Tracking page views for more information. |
config.defaultTracking.sessions |
Optional. boolean |
Enables/disables session tracking. If value is true , Amplitude tracks session start and session end events otherwise session tracking is disabled. Default value is true .See Tracking sessions for more information. |
config.defaultTracking.formInteractions |
Optional. boolean |
Enables/disables form interaction tracking. If value is true , Amplitude tracks form start and form submit events otherwise form interaction tracking is disabled. Default value is true .Event properties tracked includes: [Amplitude] Form ID , [Amplitude] Form Name , [Amplitude] Form Destination See Tracking form interactions for more information. |
config.defaultTracking.fileDownloads |
Optional. boolean |
Enables/disables file download tracking. If value is true , Amplitude tracks file download events otherwise file download tracking is disabled. Default value is true .Event properties tracked includes: [Amplitude] File Extension , [Amplitude] File Name , [Amplitude] Link ID , [Amplitude] Link Text , [Amplitude] Link URL See Tracking file downloads for more information. |
Note
The events above are tracked by default with no configuration needed. Amplitude may add more events in a future version, and the default configuration enables tracking for those events as well.
To opt-out, refer to the code below. Otherwise, you can omit the configuration to keep them enabled.
amplitude.init(AMPLITUDE_API_KEY, {
defaultTracking: {
attribution: false,
pageViews: false,
sessions: false,
formInteractions: false,
fileDownloads: false,
},
});
Alternatively, you can disable Amplitude from tracking all events mentioned above (and future default events) by setting config.defaultTracking
to false
.
amplitude.init(AMPLITUDE_API_KEY, {
defaultTracking: false,
});
Tracking marketing attribution¶
Amplitude marketing attribution by default by tracking UTM, referrers and click IDs as user properties.
Attribution Overview
Amplitude tracks marketing attribution to identify your user's traffic source using the UTM, referrer and click ID parameters.
UTM parameters¶
UTM (Urchin Traffic Monitor) parameters are useful for analyzing the effectiveness of different ad campaigns and referring sites. UTM parameters are case-sensitive, so they're treated as different values when the capitalization varies.
There are five different standard UTM parameters:
Name |
Description |
---|---|
utm_source |
This identifies which website sent the traffic (for example, Google, Facebook) |
utm_medium |
This identifies a specific campaign used (for example, "summer_sale") |
utm_campaign |
This identifies a specific campaign used (for example, "summer_sale") |
utm_term |
This identifies paid search terms used (for example, product+analytics) |
utm_content |
This identifies what brought the user to the site and is commonly used for A/B testing (for example, "banner-link", "text-link") |
Here is an example URL with UTM parameters:
https://www.amplitude.com/?utm_source=newsletter&utm_campaign=product_analytics_playbook&utm_medium=email&utm_term=product%20analytics&utm_content=banner-link
Referrer parameters¶
Referrer is the URL of the page that linked to the destination page. Amplitude tracks the following parameters:
Name |
Description |
---|---|
referrer |
The last page the user was on (for example, https://amplitude.com/behavioral-analytics-platform?ref=nav ) |
referring_domain |
The domain that the user was last on (for example, https://amplitude.com ) |
Referrer is an empty string (''
) if the user navigated to the destination page directly.
Click ID parameters¶
Click IDs are campaign identifiers included as URL query parameters. Ad platforms use these IDs to identify the campaign and other attributes. While Amplitude doesn't have access to further campaign attributes associated to Click IDs, Amplitude can track Click ID values specified in the following table.
Name |
Description |
---|---|
dclid |
Google Click Identifier from URL parameters |
fbclid |
Facebook Click Identifier from URL parameters |
gbraid |
Google campaign manager Click Identifier |
gclid |
Google Click Identifier for iOS device from Web to App |
ko_click_id |
Google Click Identifier for iOS device from App to Web |
li_fat_id |
Kochava Click Identifier from URL parameters |
msclkid |
Microsoft Click Identifier |
rtd_cid |
TikTok Click Identifier |
ttclid |
Twitter Click Identifier from URL parameter |
twclid |
Linkedin Click identifier |
wbraid |
Reddit campaign tracking/attribution Click identifier |
First-touch attribution¶
Amplitude captures the initial attribution data at the start of the first session. The first-touch attribution values are set when a user's attribution data are seen for the first time. The following user properties are set one time:
initial_utm_source
initial_utm_medium
initial_utm_campaign
initial_utm_term
initial_utm_content
initial_referrer
initial_referring_domain
initial_gclid
initial_fbclid
initial_dclid
initial_gbraid
initial_ko_click_id
initial_msclkid
initial_ttclid
initial_twclid
initial_wbraid
initial_li_fat_id
initial_rdt_cid
Multi-touch attribution¶
Amplitude captures the attribution data at the start of each session, and sets those values as user properties. For organic or direct traffic, these properties may not be available. Therefore, these user properties are unset from user identity.
For every new campaign (when new attribution data is seen), Amplitude captures the changes regardless of the state of the user session. You can configure resetSessionOnNewCampaign
to true
to reset the session on every new campaign. The default behavior is to not reset the session on new campaign.
Amplitude tracks the following as user properties:
utm_source
utm_medium
utm_campaign
utm_term
utm_content
referrer
referring_domain
gclid
fbclid
dclid
gbraid
ko_click_id
msclkid
ttclid
twclid
wbraid
li_fat_id
rdt_cid
You can opt out of marketing attribution tracking by setting config.defaultTracking.attribution
to false
. Refer to the code sample below.
amplitude.init(AMPLITUDE_API_KEY, {
defaultTracking: {
attribution: false,
},
});
Advanced configuration for tracking marketing attribution¶
You can also use advanced configuration for better control of how marketing attribution is tracked.
Marketing attribution options
Name |
Value | Description |
---|---|---|
config.defaultTracking.attribution.excludeReferrers |
Optional. Array of string or RegExp |
Sets rules to determine which referrers are excluded from being tracked as traffic source. Use string values for exact matching and RegExp values for pattern matching against the referring domain. By default the current domain (and all its subdomain) are excluded referrers. |
config.defaultTracking.attribution.initialEmptyValue |
Optional. string |
Sets the value to represent undefined/no initial campaign parameter for first-touch attribution. The default value is "EMPTY . |
config.defaultTracking.attribution.resetSessionOnNewCampaign |
Optional. boolean |
Configures Amplitude to start a new session if any campaign parameter changes. The default value is false . |
For example, you can configure Amplitude to track marketing attribution separately for each of your subdomains. Refer to the code sample for how to achieve this.
amplitude.init(AMPLITUDE_API_KEY, {
defaultTracking: {
attribution: {
excludeReferrers: [location.hostname],
},
},
});
Tracking page views¶
Amplitude tracks page view events by default. The default behavior sends a page view event on initialization. The event type for this event is "[Amplitude] Page Viewed".
You can opt out of page view tracking by setting config.defaultTracking.pageViews
to false
. Refer to the code sample below.
amplitude.init(AMPLITUDE_API_KEY, {
defaultTracking: {
pageViews: false,
},
});
Advanced configuration for tracking page views¶
You can also use advanced configuration for better control of when page view events are sent.
Tracking page views options
Name |
Value | Description |
---|---|---|
config.defaultTracking.pageViews.trackOn |
Optional. "attribution" or () => boolean |
Provides advanced control on when page view events are tracked. You can omit or set the value to undefined , and configure page view events to be tracked on initialization.You can set the value to "attribution" and configure page view events to be tracked only when web attribution are tracked.You can set the value to a function that returns a boolean ( true or false ) and configure page view events to be tracked based on your criteria. |
config.defaultTracking.pageViews.trackHistoryChanges |
Optional. "pathOnly" or "all" |
Provides advanced control for single page application on when page views are tracked. You can omit or set the value to "all" , and configure page view events to be tracked on any navigation change to the URL within your single page application. For example: navigating from https://amplitude.com/#company to https://amplitude.com/#blog .Set the value to "pathOnly", and configure page view events to be tracked on navigation change to the URL path only within your single page application. For example: navigating from https://amplitude.com/company to https://amplitude.com/blog . |
config.defaultTracking.pageViews.eventType |
Optional. string |
Customize the event_type for page view event. |
For example, you can configure Amplitude to track page views only when the URL path contains a certain substring, let’s say “home”. Refer to the code sample for how to achieve this.
amplitude.init(API_KEY, OPTIONAL_USER_ID, {
defaultTracking: {
pageViews: {
trackOn: () => {
return window.location.pathname.includes('home');
},
},
},
});
The following information is tracked in the page view events.
Name |
Description | Default Value |
---|---|---|
event_type |
string . The event type for page view event. Configurable through defaultTracking.pageViews.eventType or enrichment plugin. |
[Amplitude] Page Viewed from version 1.9.1. |
event_properties.[Amplitude] Page Domain |
string . The page domain. |
location.hostname or ''. |
event_properties.[Amplitude] Page Location |
string . The page location. |
location.href or ''. |
event_properties.[Amplitude] Page Path |
string . The page path. |
location.path or ''. |
event_properties.[Amplitude] Page Title |
string . The page title. |
document.title or ''. |
event_properties.[Amplitude] Page URL |
string . The value of page url. |
location.href.split('?')[0] or ``. |
event_properties.${CampaignParam} |
string . The value of UTMParameters ReferrerParameters ClickIdParameters if has any. Check here for the possible keys. |
Any undefined campaignParam or undefined . |
Check this example to understand how to enrich default page view events, such as adding more properties along with page view tracking.
Tracking sessions¶
Amplitude tracks session events by default. A session is the period of time a user has your website open. See How Amplitude defines sessions for more information. When a new session starts, Amplitude tracks a session start event and is the first event of the session. The event type for session start is "[Amplitude] Start Session". When an existing session ends, a session end is tracked and is the last event of the session. The event type for session end is "[Amplitude] End Session".
You can opt out of session tracking by setting config.defaultTracking.sessions
to false
. Refer to the code sample below.
amplitude.init(AMPLITUDE_API_KEY, {
defaultTracking: {
sessions: false,
},
});
Tracking form interactions¶
Amplitude tracks form interaction events by default. A form start event is tracked when the user initially interacts with the form. An initial interaction can be the first change to a text input, radio button, or dropdown. The event type for session start is "[Amplitude] Form Started". A form submit event is tracked when the user submits the form. The event type for session start is "[Amplitude] Form Submitted". If a form is submitted with no initial change to any form fields, both "[Amplitude] Form Started" and "[Amplitude] Form Submitted" are tracked.
Amplitude can track forms that are constructed with <form>
tags and <input>
tags nested. For example:
<form id="subscriber-form" name="subscriber-form" action="/subscribe">
<input type="text" />
<input type="submit" />
</form>
You can opt out of form interaction tracking by setting config.defaultTracking.formInteractions
to false
. Refer to the code sample below.
amplitude.init(AMPLITUDE_API_KEY, {
defaultTracking: {
formInteractions: false,
},
});
Tracking file downloads¶
Amplitude tracks file download events by default. A file download event is tracked when an anchor or <a>
tag linked to a file is clicked. The event type for file download is "[Amplitude] File Downloaded". Amplitude determines that the anchor or <a>
tag linked to a file if the file extension matches the following regex:
pdf|xlsx?|docx?|txt|rtf|csv|exe|key|pp(s|t|tx)|7z|pkg|rar|gz|zip|avi|mov|mp4|mpe?g|wmv|midi?|mp3|wav|wma
You can opt out of tracking file download events by setting config.defaultTracking.fileDownloads
to false
. Refer to the code sample below.
amplitude.init(AMPLITUDE_API_KEY, {
defaultTracking: {
fileDownloads: false,
},
});
User properties¶
User properties are details like device details, user preferences, or language to help you understand your users at the time they performed an action in your app.
Identify is for setting the user properties of a particular user without sending any event. The SDK supports the operations set
, setOnce
, unset
, add
, append
, prepend
, preInsert
, postInsert
, and remove
on individual user properties. Declare the operations via a provided Identify interface. You can chain together multiple operations in a single Identify object. The Identify object is then passed to the Amplitude client to send to the server.
Note
If the Identify call is sent after the event, the results of operations are visible immediately in the dashboard user’s profile area. However, they don't appear in chart results until another event is sent after the Identify call. The identify call only affects events going forward. More details here.
Set a user property¶
The Identify object provides controls over setting user properties. It works like this: first, instantiate an Identify object, then call Identify methods on it, and finally, the client can make a call with the Identify object.
const identifyEvent = new amplitude.Identify();
amplitude.identify(identifyEvent);
Identify.set¶
This method sets the value of a user property. For example, you can set a role property of a user.
const identifyEvent = new amplitude.Identify();
identifyEvent.set('location', 'LAX');
amplitude.identify(identifyEvent);
Identify.setOnce¶
This method sets the value of a user property only one time. Subsequent calls using setOnce()
are ignored. For example, you can set an initial login method for a user and because only the initial value is tracked, setOnce()
ignores later calls.
const identifyEvent = new amplitude.Identify();
identifyEvent.setOnce('initial-location', 'SFO');
identify(identifyEvent);
Identify.add¶
This method increments a user property by some numerical value. If the user property doesn't have a value set yet, it's initialized to 0 before it's incremented. For example, you can track a user's travel count.
const identifyEvent = new amplitude.Identify();
identifyEvent.add('travel-count', 1);
amplitude.identify(identifyEvent);
Arrays in user properties¶
You can use arrays as user properties. Directly set arrays or use prepend
, append
, preInsert
and postInsert
to generate an array.
Identify.prepend¶
This method prepends a value or values to a user property array. If the user property doesn't have a value set yet, it's initialized to an empty list before the new values are prepended.
const identifyEvent = new Identify();
identifyEvent.prepend('visited-locations', 'LAX');
identify(identifyEvent);
Identify.append¶
This method appends a value or values to a user property array. If the user property doesn't have a value set yet, it's initialized to an empty list before the new values are prepended.
const identifyEvent = new amplitude.Identify();
identifyEvent.append('visited-locations', 'SFO');
amplitude.identify(identifyEvent);
Identify.preInsert¶
This method pre-inserts a value or values to a user property if it doesn't exist in the user property yet. Pre-insert means inserting the values at the beginning of a given list. If the user property doesn't have a value set yet, it's initialized to an empty list before the new values are pre-inserted. If the user property has an existing value, this method is a no-op.
const identifyEvent = new amplitude.Identify();
identifyEvent.preInsert('unique-locations', 'LAX');
identify(identifyEvent);
Identify.postInsert¶
This method post-inserts a value or values to a user property if it doesn't exist in the user property yet. Post-insert means inserting the values at the end of a given list. If the user property doesn't have a value set yet, it's initialized to an empty list before the new values are post-inserted. If the user property has an existing value, this method is a no-op..
const identifyEvent = new amplitude.Identify();
identifyEvent.postInsert('unique-locations', 'SFO');
amplitude.identify(identifyEvent);
Identify.remove¶
This method removes a value or values to a user property if it exists in the user property. Remove means remove the existing values from the given list. If the user property has an existing value, this method is a no-op.
const identifyEvent = new amplitude.Identify();
identifyEvent.remove('unique-locations', 'JFK')
amplitude.identify(identifyEvent);
User groups¶
Feature availability
This feature is available in accounts with a Growth or Enterprise plan with the Accounts add-on.
Amplitude supports assigning users to groups and performing queries, such as Count by Distinct, on those groups. If at least one member of the group has performed the specific event, then the count includes the group.
For example, you want to group your users based on what organization they're in by using an 'orgId'. Joe is in 'orgId' '10', and Sue is in 'orgId' '15'. Sue and Joe both perform a certain event. You can query their organizations in the Event Segmentation Chart.
When setting groups, define a groupType
and groupName
. In the previous example, 'orgId' is the groupType
and '10' and '15' are the values for groupName
. Another example of a groupType
could be 'sport' with groupName
values like 'tennis' and 'baseball'.
Setting a group also sets the groupType:groupName
as a user property, and overwrites any existing groupName
value set for that user's groupType, and the corresponding user property value. groupType
is a string, and groupName
can be either a string or an array of strings to indicate that a user is in multiple groups.
Example
If Joe is in 'orgId' '15', then the groupName
would be '15'.
// set group with a single group name
amplitude.setGroup('orgId', '15');
If Joe is in 'sport' 'soccer' and 'tennis', then the groupName
would be '["tennis", "soccer"]'.
// set group with multiple group names
amplitude.setGroup('sport', ['soccer', 'tennis']);
You can also set event-level groups by passing an Event
Object with groups
to track
. With event-level groups, the group designation applies only to the specific event being logged, and doesn't persist on the user unless you explicitly set it with setGroup
.
amplitude.track({
event_type: 'event type',
event_properties: { eventPropertyKey: 'event property value' },
groups: { 'orgId': '15' }
})
Group properties¶
Feature availability
This feature is available in accounts with a Growth or Enterprise plan with the Accounts add-on.
Use the Group Identify API to set or update the properties of particular groups. These updates only affect events going forward.
The groupIdentify()
method accepts a group type and group name string parameter, as well as an Identify object that's applied to the group.
const groupType = 'plan';
const groupName = 'enterprise';
const groupIdentifyEvent = new amplitude.Identify()
groupIdentifyEvent.set('key1', 'value1');
amplitude.groupIdentify(groupType, groupName, groupIdentifyEvent);
Revenue tracking¶
The preferred method of tracking revenue for a user is to use revenue()
in conjunction with the provided Revenue interface. Revenue instances store each revenue transaction and allow you to define several special revenue properties (such as 'revenueType' and 'productIdentifier') that are used in Amplitude's Event Segmentation and Revenue LTV charts. These Revenue instance objects are then passed into revenue()
to send as revenue events to Amplitude. This lets automatically display data relevant to revenue in the platform. You can use this to track both in-app and non-in-app purchases.
To track revenue from a user, call revenue each time a user generates revenue. In this example, 3 units of a product were purchased at $3.99.
const event = new amplitude.Revenue()
.setProductId('com.company.productId')
.setPrice(3.99)
.setQuantity(3);
amplitude.revenue(event);
Revenue interface¶
Name |
Description | Default Value |
---|---|---|
product_id |
Optional. string . An identifier for the product. Amplitude recommend something like the Google Play Store product ID. |
Empty string. |
quantity |
Required. number . The quantity of products purchased. Note: revenue = quantity * price. |
1 |
price |
Required. number . The price of the products purchased, and this can be negative. Note: revenue = quantity * price. |
null |
revenue_type |
Optional, but required for revenue verification. string . The revenue type (for example, tax, refund, income). |
null |
receipt |
Optional. string . The receipt identifier of the revenue. |
null |
receipt_sig |
Optional, but required for revenue verification. string . The receipt signature of the revenue. |
null |
properties |
Optional. { [key: string]: any } . An object of event properties to include in the revenue event. |
null |
Flush the event buffer¶
The flush
method triggers the client to send buffered events immediately.
amplitude.flush();
By default, flush
is called automatically in an interval, if you want to flush the events altogether, you can control the async flow with the optional Promise interface, for example:
amplitude.init(API_KEY).promise.then(function() {
amplitude.track('Button Clicked');
amplitude.flush();
});
Custom user ID¶
If your app has its login system that you want to track users with, you can call setUserId
at any time.
amplitude.setUserId('user@amplitude.com');
Custom session ID¶
You can assign a new Session ID using setSessionId
. When setting a custom session ID, make sure the value is in milliseconds since epoch (Unix Timestamp).
amplitude.setSessionId(Date.now());
Custom device ID¶
If your app has its login system that you want to track users with, you can call setUserId
at any time.
You can assign a new device ID using deviceId
. When setting a custom device ID, make sure the value is sufficiently unique. Amplitude recommends using a UUID.
amplitude.setDeviceId(uuid());
Reset when user logs out¶
reset
is a shortcut to anonymize users after they log out, by:
- setting
userId
toundefined
- setting
deviceId
to a new UUID value
With an undefined userId
and a completely new deviceId
, the current user would appear as a brand new user in dashboard.
amplitude.reset();
Opt users out of tracking¶
You can turn off logging for a given user by setting setOptOut
to true
.
amplitude.setOptOut(true);
Events aren't saved or sent to the server while setOptOut
is enabled, and the setting persists across page loads.
Re-enable logging by setting setOptOut
to false
.
amplitude.setOptOut(false);
Optional tracking¶
By default, the SDK tracks these properties automatically. You can override this behavior by passing a configuration called trackingOptions
when initializing the SDK, setting the appropriate options to false.
Tracking Options | Default |
---|---|
ipAddress |
true |
language |
true |
platform |
true |
amplitude.init(AMPLITUDE_API_KEY, {
trackingOptions: {
ipAddress: false,
language: false,
platform: false,
},
});
Callback¶
All asynchronous APIs are optionally awaitable through a Promise interface. This also serves as a callback interface.
amplitude.init("apikey", "12321.com").promise.then(function(result) {
// init callback
})
amplitude.track('Button Clicked').promise.then(function(result) {
result.event; // {...} (The final event object sent to Amplitude)
result.code; // 200 (The HTTP response status code of the request.
result.message; // "Event tracked successfully" (The response message)
});
// Using async/await
const initResult = await amplitude.init("apikey", "12321.com").promise;
const results = await amplitude.track('Button Clicked').promise;
result.event; // {...} (The final event object sent to Amplitude)
result.code; // 200 (The HTTP response status code of the request.
result.message; // "Event tracked successfully" (The response message)
Plugins¶
Plugins allow you to extend Amplitude SDK's behavior by, for example, modifying event properties (enrichment plugin) or sending to third-party endpoints (destination plugin). A plugin is an Object
with optional fields name
and type
and methods setup()
, execute()
and teardown()
.
add
¶
The add
method adds a plugin to Amplitude.
amplitude.add(new Plugin());
remove
¶
The remove
method removes the given plugin name from the client instance if it exists.
amplitude.remove(plugin.name);
Create your custom plugin¶
plugin.name [optional]¶
The name field is an optional property that allows you to reference the plugin for deletion purposes. If not provided, Amplitude will assign a random name when the plugin is added. If you do not plan to delete your plugin, you can skip assigning a name.
plugin.type [optional]¶
The type field is an optional property that defines the type of plugin you are creating. Refer to execute()
function below to distinguish the two types. If not defined, the plugin defaults to an enrichment type.
plugin.setup() [optional]¶
The setup function is an optional method and is called when the plugin is added or on first init whichever happens later. This function accepts two parameters: 1) Amplitude configuration; and 2) Amplitude instance. This is useful for setup operations and tasks that depend on either the Amplitude configuration or instance. Examples include assigning baseline values to variables, setting up event listeners, and many more.
plugin.execute() [optional for type: enrichment]¶
For enrichment plugins, execute function is an optional method and is called on each event. This function must return a new event, otherwise, the passed event is dropped from the queue. This is useful for cases where you need to add/remove properties from events, filter events, or perform any operation for each event tracked.
For destination plugins, execute function is a required method and is called on each event. This function must return a response object with keys: event
(BaseEvent), code
(number), and message
(string). This is useful for sending events for third-party endpoints.
plugin.teardown() [optional]¶
The teardown function is an optional method and is called when Amplitude re-initializes. This is useful for resetting unneeded persistent state created/set by setup or execute methods. Examples include removing event listeners, mutation observers, etc.
Plugin examples¶
Enrichment plugin¶
Here's an example of an enrichment plugin that includes an additional event property page_url
to all events.
const enrichPageUrlPlugin = (): EnrichmentPlugin => {
return {
execute: async (event: Event) => {
event.event_properties = {
...event.event_properties,
page_url: location.href,
};
return event;
},
}
}
amplitude.init(API_KEY);
amplitude.add(enrichPageUrlPlugin());
Destination plugin¶
Here's an example of a destination plugin that sends each tracked event to a custom server URL using Fetch API.
const customDestination = (customUrl: string): DestinationPlugin => {
return {
type: 'destination',
execute: async (event: Event) => {
const payload = {
k: 'apikey',
d: event,
};
const response = await fetch(customUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: '*/*',
},
body: JSON.stringify(payload),
});
return {
code: response.status,
event: event,
message: response.statusText,
};
},
};
};
amplitude.init(API_KEY);
amplitude.add(myDestinationPlugin('https://custom.url.com'));
Troubleshooting and Debugging¶
How to debug¶
Debugging in a browser can help you identify problems related to your code's implementation, as well as potential issues within the SDKs you're using. Here's a basic guide on how to use the browser's built-in Developer Tools (DevTools) for debugging.
Console¶
You can find JavaScript errors under Inspect > Console, which might have the details about the line of code and file that caused the problem. The console also allows you to execute JavaScript code in real time.
-
Enable debug mode by following these instructions. Then With the default logger, extra function context information will be output to the developer console when any SDK public method is invoked, which can be helpful for debugging.
-
Amplitude supports SDK deferred initialization. Events tracked before initialization will be dispatched after the initialization call. If you cannot send events but can send the event successfully after entering
amplitude.init(API_KEY, 'USER_ID')
in the browser console, it indicates that youramplitude.init
call might not have been triggered in your codebase or you are not using the correct amplitude instance during initialization. Therefore, please check your implementation."
Network Request¶
Use the Inspect > Network tab to view all network requests made by your page. Search for the Amplitude request.
Please check the response code and ensure that the response payload is as expected.
Instrumentation Explorer/Chrome Extension¶
The Amplitude Instrumentation Explorer is an extension available in the Google Chrome Web Store. The extension captures each Amplitude event you trigger and displays it in the extension popup. It's important to ensure that the event has been sent out successfully and to check the context in the event payload.
Check here for more details.
Common Issues¶
The following are common issues specific to Browser SDK. For additional general common issues, please refer to this document.
AD Blocker¶
Ad Blocker
might lead to event dropping. The following errors indicate that the tracking has been affected by Ad Blocker
. When loading via a script tag, an error may appear in the console/network tab while loading the SDK script. When loaded with npm package, there could be errors in the network tab when trying to send events to the server. The errors might vary depending on the browser.
- Chrome (Ubuntu, MacOS) Console: error net::ERR_BLOCKED_BY_CLIENT Network: status (blocked:other)
- Firefox (Ubuntu) Console: error text doesn’t contain any blocking-specific info Network: Transferred column contains the name of plugin Blocked by uBlock Origin
- Safari (MacOS) Console: error contains text Content Blocker prevented frame ... from loading a resource from ... Network: it looks like blocked requests are not listed. Not sure if it’s possible to show them.
We recommend using a proxy server to avoid this situation.
Cookies related¶
Here is the information SDK stored in the cookies. This means that client behavior, like disabling cookies or using a private browser/window/tab, will affect the persistence of these saved values in the cookies. So, if these values are not persistent or are not increasing by one, that could be the reason.
CORS¶
Cross-Origin Resource Sharing (CORS) is a security measure implemented by browsers to restrict how resources on a web page can be requested from a different domain. It might cause this issue if you used setServerURL
.
Access to fetch at 'xxx' from origin 'xxx' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Cross-origin resource sharing (CORS) prevents a malicious site from reading another site's data without permission. The error message suggests that the server you're trying to access is not allowing your origin to access the requested resource. This is due to the lack of the Access-Control-Allow-Origin
header in the server's response.
-
If you have control over the server, you can "Update the server's CORS policy". Add the
Access-Control-Allow-Origin
header to the server's responses. This would allow your origin to make requests. The value ofAccess-Control-Allow-Origin
can be * to allow all origins, or it can be the specific URL of your web page. -
If you don't have control over the server, you can set up a proxy server that adds the necessary CORS headers. The web page makes requests to the proxy, which then makes requests to the actual server. The proxy adds the
Access-Control-Allow-Origin
header to the response before sending it back to the web page.
If you have set up an API proxy and run into configuration issues related to that on a platform you’ve selected, that’s no longer an SDK issue but an integration issue between your application and the service provider.
Events fired but no network requests¶
If you set the logger to "Debug" level, and see track calls in the developer console, the track()
method has been called. If you don't see the corresponding event in Amplitude, the Amplitude Instrumentation Explorer Chrome extension, or the network request tab of the browser, the event wasn't sent to Amplitude. Events are fired and placed in the SDK's internal queue upon a successful track()
call, but sometimes these queued events may not send successfully. This can happen when an in-progress HTTP request is cancelled. For example, if you close the browser or leave the page.
There are two ways to address this issue:
-
If you use standard network requests, set the transport to
beacon
during initialization or set the transport tobeacon
upon page exit.sendBeacon
doesn't work in this case because it sends events in the background, and doesn't return server responses like4xx
or5xx
. As a result, it doesn't retry on failure.sendBeacon
sends only scheduled requests in the background. For more information, see the sendBeacon section. -
To make track() synchronous, add the
await
keyword before the call.
Advanced topics¶
Cross-domain tracking¶
You can track anonymous behavior across two different domains. Amplitude identifies anonymous users by their device IDs which must be passed between the domains. For example:
- Site 1:
www.example.com
- Site 2:
www.example.org
Users who start on Site 1 and then navigate to Site 2 must have the device ID generated from Site 1 passed as a parameter to Site 2. Site 2 then needs to initialize the SDK with the device ID.
The SDK can parse the URL parameter automatically if deviceId
is in the URL query parameters.
- From Site 1, grab the device ID from
getDeviceId()
. - Pass the device ID to Site 2 via a URL parameter when the user navigates. (for example:
www.example.com?deviceId=device_id_from_site_1
) - Initialize the Amplitude SDK on Site 2 with
init('API_KEY', null)
.
If the deviceId
isn't provided with the init
like init('API_KEY', null, { deviceId: 'custom-device-id' })
, then it automatically fallbacks to using the URL parameter.
Use sendBeacon¶
Unlike standard network requests, sendBeacon sends events in the background, even if the user closes the browser or leaves the page.
Warning
Because sendBeacon
sends events in the background, events dispatched from sendBeacon
don't return a server response and can't be retried when they encounter failures like 4xx or 5xx errors. You can address these retry issues by sending one event/request, but this could increase the network load and the likelihood of throttling.
Set the transport to use sendBeacon for all events¶
To send an event using sendBeacon
, set the transport SDK option to 'beacon' in one of two ways
amplitude.init(API_KEY, 'user@amplitude.com',
{
transport: TransportType.SendBeacon,
// To make sure the event will be scheduled right away.
flushIntervalMillis: 0,
flushQueueSize: 1,
}
);
Set the transport to use beacon only when exiting page¶
Amplitude recommends adding your own event listener for pagehide event.
window.addEventListener('pagehide',
() => {
amplitude.setTransport('beacon')
// Sets https transport to use `sendBeacon` API
amplitude.flush()
},
);
Content Security Policy (CSP)¶
If your web app configures the strict Content Security Policy (CSP) for security concerns, adjust the policy to whitelist the Amplitude domains:
- When using "Script Loader", add
https://*.amplitude.com
toscript-src
. - Add
https://*.amplitude.com
toconnect-src
.
Cookie management¶
The Browser SDK uses cookie storage to persist information that multiple subdomains of the same domain may likely want to share. This includes information like user sessions and marketing campaigns, which are stored in separate cookie entries.
Cookie prefix¶
- AMP: The SDK creates user session cookies with
AMP
prefix and the first ten digits of the API key:AMP_{first_ten_digits_API_KEY}
. - AMP_MKTG: The SDK creates marketing campaign cookies with
AMP_MKTG
and the first ten digits of the API key:AMP_MKTG_{first_ten_digits_API_KEY}
. - AMP_TEST: On initialization, the SDK creates a cookie with
AMP_TEST
prefix to check whether the cookie storage is working properly. Then the SDK sets the value as the current time, retrieves the cookie by a key and checks if the retrieved value matches the original set time. You can safely delete theAMP_TEST
prefix cookies if, for some reason, they're not successfully deleted. - AMP_TDLTEST: On initialization, the SDK creates a cookie with
AMP_TDLTEST
prefix to find a subdomain that supports cookie storage. For example, when checking for cookie support onhttps://analytics.amplitude.com/amplitude/home
the SDK first tries to find a subdomain that matches the root domain (amplitude.com
) and then falls back to the full domain (analytics.amplitude.com
). You can safely delete theAMP_TDLTEST
prefix cookies if, for some reason, they're not successfully deleted.
Cookie domain¶
By default, the SDK assigns these cookies to the top-level domain which supports cookie storage. Cookies can be shared on multiple subdomains which allows for a seamless user experience across all subdomains.
For example, if a user logs into the website on one subdomain (data.amplitude.com
) where the SDK is initialized. On initialization, the SDK assigns cookies to .amplitude.com
. If the user then navigates to another subdomain (analytics.amplitude.com
), the login information can be seamlessly shared by shared cookies.
Cookie data¶
The SDK creates two types of cookies: user session cookies and marketing campaign cookies.
User session cookies
Name |
Description |
---|---|
optOut |
Required. A flag to opt this device out of Amplitude tracking. If this flag is set, no additional information will be stored for the user |
userId |
Upon user log-in, if you send this value, it is stored in the cookie. Set this to uniquely identify their users (non-anonymous navigation). It is stored encoded using Base64 |
deviceId |
A randomly generated string. It will persist unless a user clears their browser cookies and/ or is browsing in private mode. Even if a user consistently uses the same the device and browser, the device ID can still vary |
sessionId |
A randomly generated string for each session |
lastEventTime |
Time of the last event, used to determine when to expire and create a new session Id |
lastEventId |
Id of the last event |
Marketing campaign cookies
Name |
Description |
---|---|
utm_campaign |
This identifies a specific campaign used (for example, "summer_sale") |
utm_content |
This identifies what brought the user to the site and is commonly used for A/B testing (for example, "banner-link", "text-link") |
utm_id |
An optional parameter for tracking unique IDs or transaction IDs associated with the link. |
utm_medium |
This identifies a specific campaign used (for example, "summer_sale") |
utm_source |
This identifies which website sent the traffic (for example, Google, Facebook) |
utm_term |
This identifies paid search terms used (for example, product+analytics) |
referrer |
The last page the user was on (for example, https://amplitude.com/behavioral-analytics-platform?ref=nav ) |
referring_domain |
The domain that the user was last on (for example, https://amplitude.com ) |
dclid |
Google campaign manager Click Identifier |
gbraid |
Google Click Identifier for iOS device from Web to App |
gclid |
Google Click Identifier from URL parameters |
fbclid |
Facebook Click Identifier from URL parameters |
ko_click_id |
Kochava Click Identifier from URL parameters |
msclkid |
Microsoft Click Identifier |
ttclid |
TikTok Click Identifier |
twclid |
Twitter Click Identifier from URL parameter |
wbraid |
Google Click Identifier for iOS device from App to Web |
li_fat_id |
LinkedIn member indirect identifier for Members for conversion tracking, retargeting, analytics |
rtd_cid |
Reddit Click Identifier |
Disable cookies¶
You can opt-out of using cookies by setting disableCookies
to true
so that the SDK will use LocalStorage
instead. LocalStorage
is a great alternative, but because access to LocalStorage
is restricted by subdomain, you can't track anonymous users across subdomains of your product (for example: www.amplitude.com
vs analytics.amplitude.com
).