Amplitude's Browser SDK 2 lets you send events to Amplitude.
Install the dependency with npm, yarn, or the script loader.
<script src="https://cdn.amplitude.com/script/AMPLITUDE_API_KEY.js"></script>
<script>
window.amplitude.init('AMPLITUDE_API_KEY', {
fetchRemoteConfig: true,
autocapture: true
});
</script>
<script src="https://cdn.eu.amplitude.com/script/AMPLITUDE_API_KEY.js"></script>
<script>
window.amplitude.init('AMPLITUDE_API_KEY', {
serverZone: 'EU',
fetchRemoteConfig: true,
autocapture: true
});
</script>
# Install Analytics SDK only
npm install @amplitude/analytics-browser
# Or install Unified SDK to get access to all Amplitude products
npm install @amplitude/unified
Import Amplitude into your project
// If using Analytics SDK only
import * as amplitude from '@amplitude/analytics-browser';
// If using Unified SDK
import * as amplitude from '@amplitude/unified';
# Install Analytics SDK only
yarn add @amplitude/analytics-browser
# Or install Unified SDK to get access to all Amplitude products
yarn add @amplitude/unified
Import Amplitude into your project
// If using Analytics SDK only
import * as amplitude from '@amplitude/analytics-browser';
// If using Unified SDK
import * as amplitude from '@amplitude/unified';
event_type field and at least one of deviceId (included by default) or userId, and follow 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 userId or deviceId value, Amplitude may reject the upload with a 400 status. Override the default minimum length of 5 characters by setting the minIdLength config option.
This SDK requires initialization before you can instrument any events and requires your Amplitude project's API key. You can pass an optional userID and config object in this call.
// 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);
init outside of the Angular zone.
runOutsideAngular(function () { amplitude.init(...args); })
The Angular zone overwrites certain DOM functions that, when invoked by Amplitude autocapture, causes some user interactions to break
SDK configuration options
Name
Description
Default Value
instanceNamestring. The instance name.$default_instance
flushIntervalMillisnumber. Sets the interval of uploading events to Amplitude in milliseconds.1,000 (1 second)
flushQueueSizenumber. Sets the maximum number of events batched in a single upload attempt.30 events
flushMaxRetriesnumber. Sets the maximum number of retries for failed upload attempts. This is only applicable to errors that the SDK can retry.5 times.
logLevelLogLevel.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 that implements the Logger interface to emit log messages to a specified destination.Amplitude Logger
minIdLengthnumber. Sets the minimum length for the value of userId and deviceId properties.5
optOutboolean. Sets permission to track events. Setting a value of true prevents Amplitude from tracking and uploading events.false
serverUrlstring. Sets the URL where events are upload to.https://api2.amplitude.com/2/httpapi
serverZoneEU or US. Sets the Amplitude server zone. Set this to EU for Amplitude projects created in EU data center.US
useBatchboolean. Sets whether to upload events to Batch API instead of the default HTTP V2 API or not.false
appVersionstring. Sets an app version for events tracked. This can be the version of your application. For example: "1.0.0"undefined
autocaptureboolean|AutocaptureOptions. Configures autocapture tracking. See Autocapture.
defaultTrackingboolean. Deprecated in version 2.10.0. Use autocapture instead. Configures default event tracking.true
deviceIdstring. Sets an identifier for the device running your application.UUID()
identifyIdentify. Calls "identify" with this object during initialization. Called before Autocapture events, like session_start, ensuring proper attribution of events.undefined
cookieOptions.domainstring. Sets the domain property of cookies created.undefined
cookieOptions.expirationnumber. Sets expiration of cookies created in days.365 days
cookieOptions.sameSitestring. Sets SameSite property of cookies created.Lax
cookieOptions.secureboolean. Sets Secure property of cookies created.false
cookieOptions.upgradeboolean. 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
identityStoragestring. Sets storage API for user identity. Options include cookie for document.cookie, localStorage for localStorage, sessionStorage for sessionStorage, or none to opt-out of persisting user identity.cookie
partnerIdstring. Sets partner ID. Amplitude requires the customer who built an event ingestion integration to add the partner identifier to partner_id.undefined
sessionTimeoutnumber. Sets the period of inactivity from the last tracked event before a session expires in milliseconds.1,800,000 milliseconds (30 minutes)
storageProviderStorage<Event[]>. Sets a custom implementation of Storage<Event[]> to persist unsent events.LocalStorage
userIdstring. Sets an identifier for the tracked user. Must have a minimum length of 5 characters unless overridden with the minIdLength option.undefined
trackingOptionsTrackingOptions. Configures tracking of extra properties.Enable all tracking options by default.
transportstring. Sets request API to use by name. Options include fetch for fetch, xhr for XMLHTTPRequest, or beacon for navigator.sendBeacon.fetch
offlineboolean. Whether the SDK connects to the network. See Offline modefalse
fetchRemoteConfigboolean. Deprecated. Use remoteConfig.fetchRemoteConfig instead. Whether the SDK fetches remote configuration. See Remote configurationstrue
remoteConfigobject. Remote configuration options. See Remote configurationfetchRemoteConfig - boolean. Whether the SDK fetches remote configuration. Default: trueserverUrl - string. Custom server URL for proxying remote config requestsundefined
To support high-performance environments, the SDK sends events in batches. The SDK queues in memory every event the track method logs. Customize this behavior with the flushQueueSize and flushIntervalMillis configuration parameters. If you plan to send large batches of data at once, set useBatch to true and setServerUrl to the batch API: https://api2.amplitude.com/batch. Both standard and batch modes use the same event upload threshold and flush time intervals
To send data to Amplitude's EU-based servers, set the server zone when you initialize the client. If set, the SDK sends to the region determined by this setting.
amplitude.init(AMPLITUDE_API_KEY, {
serverZone: 'EU',
});
Control the level of logs the SDK prints to the console with the following logLevel settings:
| Log level | Description |
|---|---|
none |
Suppresses all log messages |
error |
Shows error messages only |
warn |
Default. Shows error and warning messages. |
verbose |
Shows informative messages. |
debug |
Shows all messages, including function context information for each public method the SDK invokes. Amplitude recommends this log level for development only. |
Set the logLevel parameter.
amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, {
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, OPTIONAL_USER_ID, {
loggerProvider: new MyLogger(),
});
Enable the debug mode by setting the logLevel to "Debug", for example:
amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, {
logLevel: amplitude.Types.LogLevel.Debug,
});
With the default logger, extra function context information is output to the developer console when invoking any SDK public method, including:
type: Category of this context, for example "invoke public method".name: Name of invoked function, for example "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.Starting in SDK version 2.10.0, the Browser SDK can autocapture events when you enable it, and adds a configuration to control the collection of autocaptured events. Browser SDK can autocapture the following event types:
Autocapture options
Name
Value
Description
config.autocapture.attributionOptional.
booleanEnables/disables marketing attribution tracking. If
true, Amplitude tracks marketing attribution events. Default value is true.
config.autocapture.pageViewsOptional.
booleanEnables/disables default page view tracking. If
true, Amplitude tracks page view events on initialization. Event properties tracked includes: [Amplitude] Page Domain, [Amplitude] Page Location, [Amplitude] Page Path, [Amplitude] Page Title, [Amplitude] Page URL. Default value is true. See Track page views for more information.
config.autocapture.sessionsOptional.
booleanEnables/disables session tracking. If
true, Amplitude tracks session start and session end events otherwise, Amplitude doesn't track session events. When this setting is false, Amplitude tracks sessionId only. Default value is true. See Track sessions for more information.
config.autocapture.formInteractionsOptional.
booleanEnables/disables form interaction tracking. If
true, Amplitude tracks form start and form submit events. Event properties tracked includes: [Amplitude] Form ID, [Amplitude] Form Name, [Amplitude] Form Destination. Default value is true. See Track form interactions for more information.
config.autocapture.fileDownloadsOptional.
booleanEnables/disables file download tracking. If
true, Amplitude tracks file download events otherwise. Event properties tracked includes: [Amplitude] File Extension, [Amplitude] File Name, [Amplitude] Link ID, [Amplitude] Link Text, [Amplitude] Link URL. Default value is true. See Track file downloads for more information.
config.autocapture.elementInteractionsOptional.
booleanEnables/disables element interaction tracking. If
true, Amplitude tracks clicks and form field interactions. Default value is false. See Track element interactions for more information and configuration options.
config.autocapture.frustrationInteractionsOptional.
booleanEnables/disables frustration interaction tracking. If
true, Amplitude tracks rage clicks and dead clicks. Default value is false. Review Track frustration interactions for more information and configuration options. Minimum SDK version 2.24.0
config.autocapture.pageUrlEnrichmentOptional.
booleanEnables/disables page URL enrichment tracking. If
true, Amplitude automatically adds page URL-related properties to all events, including previous page information and page type classification. Default value is true. Go to Page URL enrichment plugin for more information.
config.autocapture.networkTrackingOptional.
booleanEnables/disables capturing network request events invoked by XHR and Fetch. If
true, Amplitude tracks failed network requests. To configure what gets captured, set this as a network tracking options object. Default value is false. See Track network interactions for more information and configuration options.
Autocapture supports remote configuration. For more information, see Autocapture Settings.
To disable Autocapture, see the following code sample.
// Disable individual default tracked events
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
attribution: false,
pageViews: false,
sessions: false,
formInteractions: false,
fileDownloads: false,
elementInteractions: false,
pageUrlEnrichment: false,
},
});
// Disable all default tracked events
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: false,
});
Amplitude tracks marketing attribution by default. Browser SDK 2 captures UTM parameters, referrer information, and click IDs as user properties.
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: Here is an example URL with UTM parameters: Referrer is the URL of the page that linked to the destination page. Amplitude tracks the following parameters: Referrer is an empty string ( 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. Amplitude captures the initial attribution data at the start of the first session. The first-touch attribution values are set when Amplitude sees a user's attribution data for the first time. The following user properties are set one time: 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, Amplitude captures the changes regardless of the state of the user session. You can configure Amplitude tracks the following as user properties:Attribution overview
UTM parameters
Name
Description
utm_sourceThis identifies which website sent the traffic (for example, Google, Facebook)
utm_mediumThis identifies a specific campaign used (for example, "summer_sale")
utm_campaignThis identifies a specific campaign used (for example, "summer_sale")
utm_termThis identifies paid search terms used (for example, product+analytics)
utm_contentThis identifies what brought the user to the site and is commonly used for A/B testing (for example, "banner-link", "text-link")
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
Name
Description
referrerThe last page the user was on (for example,
https://amplitude.com/behavioral-analytics-platform?ref=nav)
referring_domainThe domain that the user was last on (for example,
https://amplitude.com)'') if the user navigated to the destination page directly.Click ID parameters
Name
Description
dclidGoogle Marketing Platform click identifier
fbclidFacebook click identifier
gbraidGoogle click identifier on iOS for web-to-app measurement
wbraidGoogle click identifier on iOS for app-to-web measurement
gclidGoogle click identifier
ko_click_idKochava click identifier
li_fat_idLinkedIn click identifier
msclkidMicrosoft click identifier
rdt_cidReddit click identifier
ttclidTikTok click identifier
twclidTwitter click identifier
First-touch attribution
initial_utm_sourceinitial_utm_mediuminitial_utm_campaigninitial_utm_terminitial_utm_contentinitial_referrerinitial_referring_domaininitial_gclidinitial_fbclidinitial_dclidinitial_gbraidinitial_ko_click_idinitial_msclkidinitial_ttclidinitial_twclidinitial_wbraidinitial_li_fat_idinitial_rdt_cidMulti-touch attribution
resetSessionOnNewCampaign to true to reset the session on every new campaign. The default behavior is to not reset the session on new campaign.
utm_sourceutm_mediumutm_campaignutm_termutm_contentreferrerreferring_domaingclidfbcliddclidgbraidko_click_idmsclkidttclidtwclidwbraidli_fat_idrdt_cid
Set config.autocapture.attribution to false to disable marketing attribution tracking.
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
attribution: false,
},
});
Marketing attribution configuration
Name
Value
Description
config.autocapture.attribution.excludeReferrersOptional. Array of
string or RegExpSets rules to decide which referrers to exclude from tracking as traffic source. Use string values for exact matching and RegExp values for pattern matching against the referring domain. When this option isn't set, the SDK excludes the current domain (and its subdomains). If explicitly adding an external referrer to exclude, you must also add the current domain (and its subdomains) as more referrers to exclude.
config.autocapture.attribution.initialEmptyValueOptional.
stringSets the value to represent undefined/no initial campaign parameter for first-touch attribution. The default value is
"EMPTY".
config.autocapture.attribution.resetSessionOnNewCampaignOptional.
booleanConfigures Amplitude to start a new session if any campaign parameter changes. The default value is
false.
config.autocapture.attribution take effect only on user properties and do NOT affect the event properties of the default page view events.The default value of config.autocapture.attribution.excludeReferrers is the top level domain with cookie storage enabled. For example, if you initialize the SDK on https://www.docs.developers.amplitude.com/, the SDK first checks amplitude.com. If it doesn't allow cookie storage, then the SDK checks developers.amplitude.com and subsequent subdomains. If it allows cookie storage, then the SDK sets excludeReferrers to an RegExp object /amplitude\.com$/ which matches and then exlucdes tracking referrers from all subdomains of amplitude.com, for example, data.amplitude.com, analytics.amplitude.com and etc.
In addition to excluding referrers from the default configuration, you can add other domains by setting the custom excludeReferrers. Custom excludeReferrers overrides the default values. For example, to also exclude referrers from google.com, set excludeReferrers to [/amplitude\.com$/, 'google.com'].
Example of including all referrers
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
attribution: {
// Override the default setting to exclude all subdomains
excludeReferrers: [],
},
},
});
Example of excluding all self-referrals and other subdomains
your-domain.com, as well as from a specific subdomain.
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
attribution: {
excludeReferrers: [/your-domain\.com$/, 'www.test.com'],
},
},
});
Exclude referrers that match a specific pattern
test.com.
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
attribution: {
excludeReferrers: [/test\.com$/],
},
},
});
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.
Set config.autocapture.pageViews to false to disable page view tracking.
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
pageViews: false,
},
});
Use the advanced configuration to better control when the SDK sends page view events.
Tracking page views options
Name
Value
Description
config.autocapture.pageViews.trackOnOptional.
"attribution" or () => booleanProvides advanced control for when the SDK tracks page view events. Omit or set the value to
undefined, and configure the SDK to track page view events to on initialization. Set the value to "attribution" and configure the SDK to track page view events to only when it tracks web attribution. Set the value to a function that returns a boolean (true or false) and configure the SDK to track page view events to based on your criteria.
config.autocapture.pageViews.trackHistoryChangesOptional.
"pathOnly" or "all"Provides advanced control for single page application for when the SDK tracks page views. Omit or set the value to
"all", and configure the SDK to track page view events 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 the SDK to track page view events 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.autocapture.pageViews.eventTypeOptional.
stringCustomize 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.
amplitude.init(API_KEY, OPTIONAL_USER_ID, {
autocapture: {
pageViews: {
trackOn: () => {
return window.location.pathname.includes('home');
},
},
},
});
Browser SDK tracks the following information in page view events.
| Name | Description | Default Value |
|---|---|---|
event_type |
string. The event type for page view event. Configurable through autocapture.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. |
Any undefined campaignParam or undefined. |
event_properties.[Amplitude] Page Counter |
integer. The count of pages viewed in the session. |
1 |
event_properties.referrer |
string. The full URL of the users previous page. |
https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2 |
event_properties.referring_domain |
string. The domain of the page referrer. amplitude.com |
Review this example to understand how to enrich default page view events, such as adding more properties along with page view tracking.
Amplitude lets you to mask page titles in events that include the [Amplitude] Page Title property. This protects your sensitive page title information. Use the data-amp-mask attribute on your <title> element to exclude the actual page title from this property.
When the <title> element has the data-amp-mask attribute, Amplitude replaces the page title with a masked value across all events that capture page title information. For example:
<head>
<!-- This page title will be masked in all events that capture page titles -->
<title data-amp-mask>John Doe - Personal Banking Dashboard</title>
</head>
<head>
<!-- Works with any attribute value -->
<title data-amp-mask="true">Sensitive Customer Information</title>
</head>
data-amp-mask triggers masking, regardless of the attribute value.[Amplitude] Page Title.data-amp-mask on individual elements***** in your event dataAmplitude 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, Amplitude tracks a session end event, which is the last event of the session. The event type for session end is [Amplitude] End Session.
You can opt out of tracking session events by setting config.autocapture.sessions to false. Refer to the code sample below.
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
sessions: false,
},
});
Amplitude tracks form interaction events by default. The SDK tracks [Amplitude] Form Started when the user initially interacts with the form element. An initial interaction can be the first change to a text input, radio button, or dropdown. The SDK tracks a [Amplitude] Form Submitted when the user submits the form. If a user submits a form with no initial change to any form fields, Amplitude tracks both [Amplitude] Form Started and [Amplitude] Form Submitted events.
Amplitude can track forms 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>
Set config.autocapture.formInteractions to false to disable form interaction tracking
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
formInteractions: false,
},
});
Amplitude tracks file download events by default. The SDK tracks [Amplitude] File Downloaded when the user clicks an anchor or <a> tag linked to a file. 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
Set config.autocapture.fileDownloads to false to disable file download tracking.
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
fileDownloads: false,
},
});
You can enable element interaction tracking to capture clicks and changes for elements on your page, which is required for Visual labeling. Review our page on Autocapture privacy and security for more information about the data collected with these events.
Set config.autocapture.elementInteractions to true to enable element click and change tracking.
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
elementInteractions: true,
},
});
Use the advanced configuration to control element interaction tracking.
Tracking element interaction options
Name
Value
Description
config.autocapture.elementInteractions.cssSelectorAllowlistOptional.
(string)[]Accepts one or more CSS selectors that define which elements on the page should always be tracked. By default, this is set to
['a','button','input','select','textarea','label','video','audio','[contenteditable="true" i]','[data-amp-default-track]','.amp-default-track']
config.autocapture.elementInteractions.actionClickAllowlistOptional.
(string)[]Accepts one or more CSS selectors that define which elements on the page should be tracked when the page changes (for example, a new visual element appears) or the click takes a user to a new page. By default, this is set to
['div', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
config.autocapture.elementInteractions.pageUrlAllowlistOptional.
(string|RegExp)[]Defines the URL, URLs, or URL pattern on which Amplitude tracks element click and change events. By default, element interactions will be captured on any URL if undefined.
config.autocapture.elementInteractions.dataAttributePrefixOptional.
(string|RegExp)[]Allows the SDK to capture data attributes as an event property. By default, this is set to
data-amp-track.
For example, you could configure Amplitude only to capture clicks on elements with a class of amp-tracking on the blog pages of a site as follows:
amplitude.init(API_KEY, OPTIONAL_USER_ID, {
autocapture: {
elementInteractions: {
cssSelectorAllowlist: [
'.amp-tracking'
],
// When you use `cssSelectorAllowlist` to target specific elements, set `actionClickAllowlist` [tl! ~~:2]
// to ensure that Amplitude tracks interactions with non-standard clickable elements during page transitions or DOM updates.
actionClickAllowlist: [],
pageUrlAllowlist: [
new RegExp('https://amplitude.com/blog/*')
]
}
}
});
By default, if you don't use these settings, Amplitude tracks the default selectors on all page on which you enable the plugin.
DEFAULT_CSS_SELECTOR_ALLOWLIST and include it in your code.
import { DEFAULT_CSS_SELECTOR_ALLOWLIST } from '@amplitude/plugin-autocapture-browser';
const selectors = [
...DEFAULT_CSS_SELECTOR_ALLOWLIST,
'.class-of-a-thing-i-want-to-track',
];
These two events capture properties that describe the corresponding element and other context about the user's browser:Element interaction events
[Amplitude] Element Clicked[Amplitude] Element Changed
[Amplitude] Element ID[Amplitude] Element Class[Amplitude] Element Tag[Amplitude] Element Text (Collected for [Amplitude] Element Clicked, only)[Amplitude] Element Href (Collected for [Amplitude] Element Clicked, only)[Amplitude] Element Position Left[Amplitude] Element Position Top[Amplitude] Viewport Height[Amplitude] Viewport Width[Amplitude] Page URL[Amplitude] Page Title[Amplitude] Element Selector[Amplitude] Element Hierarchy[Amplitude] Element Attributes[Amplitude] Element Aria Label[Amplitude] Element Parent Label
Enable frustration interaction tracking to capture rage clicks and dead clicks. Amplitude defines "rage click" and
"dead click" events as:
Set config.autocapture.frustrationInteractions to true to enable capture of dead clicks and rage clicks.
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
frustrationInteractions: true,
},
});
Use the advanced configuration to control frustration interaction tracking.
Tracking frustration interaction options
Name
Value
Description
config.autocapture.frustrationInteractions.deadClicks.cssSelectorAllowlistOptional.
(string)[]Accepts one or more CSS selectors that define the elements on which Amplitude captures dead clicks. By default, this is set to DEFAULT_DEAD_CLICK_ALLOWLIST
config.autocapture.frustrationInteractions.rageClicks.cssSelectorAllowlistOptional.
(string)[]Accepts one or more CSS selectors that define the elements on which Amplitude captures rage clicks. By default, this is set to capture on any element.
Track when network requests fail (only XHR and fetch). By default, tracks network requests with a response code in the range 500-599, excluding requests made to any amplitude.com domain.
Set config.autocapture.networkTracking to true to enable network request tracking
amplitude.init(AMPLITUDE_API_KEY, {
autocapture: {
networkTracking: true,
},
});
When you enable this setting, Amplitude tracks the [Amplitude] Network Request event whenever the application makes a network request.
Event Properties Descriptions
Event property
Description
[Amplitude] URLThe URL of the network request with sensitive information masked.
[Amplitude] URL QueryThe query parameters of the URL.
[Amplitude] URL FragmentThe fragment identifier of the URL.
[Amplitude] Request MethodThe HTTP method used for the request (GET, POST, etc.).
[Amplitude] Status CodeThe HTTP status code of the response.
[Amplitude] Error CodeThe local error code if the request failed with out a status code.
[Amplitude] Error MessageThe local error message if the request failed with out a status code.
[Amplitude] Start TimeThe timestamp when the request started, in milliseconds since Unix epoch.
[Amplitude] Completion TimeThe timestamp when the request completed, in milliseconds since Unix epoch.
[Amplitude] DurationThe duration of the request in milliseconds.
[Amplitude] Request Body SizeThe size of the request body in bytes.
[Amplitude] Response Body SizeThe size of the response body in bytes.
[Amplitude] Request BodyThe captured JSON request body (when you configure a
requestBody capture rule).
[Amplitude] Response BodyThe captured JSON response body (when you configure a
responseBody capture rule).
Set config.autocapture.networkTracking to a NetworkTrackingOptions to configure which network requests get tracked.
NetworkTrackingOptions
Name
Description
Value
captureRulesThe rules for capturing network requests. You should always append rules with specific hosts to the bottom of the list.
undefined
ignoreHostsThe hosts to ignore. Supports wildcard characters
*. For example, ["*"] to ignore all hosts, ["*.notmyapi.com", "notmyapi.com"] to ignore notmyapi.com and all subdomains.[]
ignoreAmplitudeRequestsWhether to ignore Amplitude requests.
true
NetworkTrackingOptions.NetworkCaptureRule
Name
Description
Default Value
urlsDefines the URL, URLs, or URL pattern to capture. By default captures all URLs. eg.
[/https:\/\/example.com\/api\/*/, 'https://example.com/api/status']<any>
hostsThe hosts to capture. Supports wildcard characters
*. eg. ["*"] to match all hosts, ["*.example.com", "example.com"] to match example.com and all subdomains. (this is deprecated. URLs is the preferred way to filter by hosts.)none
methodsThe HTTP methods to capture. e.g.:
["POST", "PUT", "DELETE"]['*']
statusCodeRangeThe status code range to capture. Supports comma-separated ranges or single status codes. For example,
"0,200-299,413,500-599""500-599"
requestBodyCaptures fields in the request body (go to #BodyCaptureRule).
undefined
responseBodyCaptures fields in the response body (go to #BodyCaptureRule).
undefined
requestHeadersCaptures request headers. If
true, captures safe headers. If false, no headers captured. If an array of strings, captures the specified headers.false
responseHeadersCaptures response headers. If
true, captures safe headers. If false, no headers captured. If an array of strings, captures the specified headers.false
BodyCaptureRule
Name
Description
Default Value
allowlistArray of JSON property names to capture from request/response bodies. Uses JSON Pointer syntax where leading
/ is optional. Supports wildcards: * matches any key, ** matches any number of keys. Maintains the structure of the original JSON.[]
blocklistArray of JSON property names to exclude from captured request/response bodies. This removes properties that the allowlist would otherwise capture.
[]
When you set requestHeaders: true or responseHeaders: true, Amplitude captures only safe headers and excludes sensitive ones that may contain authentication credentials or personally identifiable information.
Safe headers list
access-control-allow-originaccess-control-allow-credentialsaccess-control-expose-headersaccess-control-max-ageaccess-control-allow-methodsaccess-control-allow-headersaccept-patchaccept-rangesageallowalt-svccache-controlconnectioncontent-dispositioncontent-encodingcontent-languagecontent-lengthcontent-locationcontent-md5content-rangecontent-typedatedelta-baseetagexpiresimlast-modifiedlinklocationpermanentp3ppragmaproxy-authenticatepublic-key-pinsretry-afterserverstatusstrict-transport-securitytrailertransfer-encodingtkupgradevaryviawarningwww-authenticatex-b3-traceidx-frame-options
If a network request or response body is in JSON, you can capture part of the response body by configuring responseBody.allowlist and responseBody.blocklist. You can capture part of the request body by configuring requestBody.allowlist and requestBody.blocklist.
The allowlist and blocklist are lists of JSON Pointer-like strings that capture specific fields. (For example: ['foo/bar', 'hello/**']). allowlist tells the client which fields to capture. excludelist tells the client to exclude fields from capture (by default, nothing captured)
Example request/response body
{
"a": "A",
"b": {
"c": "C",
"d": {
"e": "E",
"f": "F"
}
},
"g": "G"
}
| allowlist | Captured Result |
|---|---|
a |
{ "a": "A" } |
a/b/* |
{ "a": { "b": { "c": "C" } } } |
b/c |
{ "b": { "c": "C" } } |
b/** |
{ "b": { "c": "C", "d": { "e": "E", "f": "F" } } } |
b/d/* |
{ "b": { "d": { "e": "E", "f": "F" } } } |
b/** |
{ "b": { "c": "C", "d": { "e": "E", "f": "F" } } |
* |
{ "a": "A", "g": "G" } |
Events represent how users interact with your application. For example, the Button Clicked event might be an action you want to track.
// 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 track. For more information, review 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);
By default, Amplitude SDKs send data to one Amplitude project. To send data to more than one project, add an instance of the Amplitude SDK for each project you want to receive data. Then, pass instance variables to wherever you want to call Amplitude. Each instance allows for independent apiKey, userId, deviceId, and settings values.
const defaultInstance = amplitude.createInstance();
defaultInstance.init(API_KEY_DEFAULT);
const envInstance = amplitude.createInstance();
envInstance.init(API_KEY_ENV, {
instanceName: 'env',
});
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 through 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.
The Identify object provides controls for setting user properties. To set a user property:
const identifyEvent = new amplitude.Identify();
// Use methods in the following sections to update the Identify object
amplitude.identify(identifyEvent);
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', 'LA');
amplitude.identify(identifyEvent);
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. setOnce() ignores later calls.
const identifyEvent = new amplitude.Identify();
identifyEvent.setOnce('initial-location', 'SF');
identify(identifyEvent);
This method increments a user property by a 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);
Call the prepend, append, preInsert, or postInsert methods to use arrays as user properties.
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);
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);
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);
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);
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 tell that a user is in multiple groups.
groupName is 15.
// set group with a single group name
amplitude.setGroup('orgId', '15');
If Joe is in 'sport' 'soccer' and 'tennis', then the groupName is ["tennis", "soccer"].
// set group with multiple group names
amplitude.setGroup('sport', ['soccer', 'tennis']);
Pass an Event object with groups to a Track call to set an event-level group. With event-level groups, the group designation applies only to the specific logged event, and doesn't persist to the user unless you explicitly set it with setGroup.
amplitude.track({
event_type: 'event type',
event_properties: { eventPropertyKey: 'event property value' },
groups: { 'orgId': '15' }
})
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);
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 (like 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, the user purchased 3 units of a product at $3.99.
const event = new amplitude.Revenue()
.setProductId('com.company.productId')
.setPrice(3.99)
.setQuantity(3);
amplitude.revenue(event);
| 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. revenue = quantity * price. |
1 |
price |
Required. number. The price of the products purchased, and this can be negative. 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 |
The flush method triggers the client to send buffered events immediately.
amplitude.flush();
By default, Browser SDK callsflush automatically at an interval. If you want to flush all events, control the async flow with the optional Promise interface, for example:
amplitude.init(API\_KEY).promise.then(function() {
amplitude.track('Button Clicked');
amplitude.flush();
});
If your application has a login system that you want to track users with, call setUserId to update the user's identifier.
amplitude.setUserId('user@amplitude.com');
Assign a new session ID with setSessionId. When you set a custom session ID, make sure the value is in milliseconds since epoch (Unix Timestamp).
amplitude.setSessionId(Date.now());
Assign a new device ID with deviceId. When you set a custom device ID, make sure the value is sufficiently unique. Amplitude recommends using a UUID.
amplitude.setDeviceId(uuid());
Use reset as a shortcut to anonymize users after they log out. reset does the following:
userId to undefined.deviceId to a new UUID value.With an undefined userId and a new deviceId, the user appears to Amplitude as a new user.
amplitude.reset();
Set setOptOut to true to disable logging for a specific user.
amplitude.setOptOut(true);
Amplitude doesn't save or send events to the server while setOptOut is enabled. The setting persists across page loads.
Set setOptOut to false to re-enable logging.
amplitude.setOptOut(false);
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,
},
});
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() {
// 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 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().
The add method adds a plugin to Amplitude.
amplitude.add(new Plugin());
The remove method removes the given plugin name from the client instance if it exists.
amplitude.remove(plugin.name);
| Field / Function | Description |
|---|---|
plugin.name |
Optional. The name field is an optional property that allows you to reference the plugin for deletion purposes. If not provided, Amplitude assigns a random name when you add the plugin. If you don't 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. See plugin.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 called when you add the plugin 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 called on each event. This function must return a new event, otherwise, the SDK drops the passed event 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 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 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 or mutation observers. |
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.add(enrichPageUrlPlugin());
amplitude.init(API_KEY);
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'));
Amplitude provides several official plugins to extend the Browser SDK functionality:
The page URL enrichment plugin is enabled by default with autocapture. It automatically adds page URL-related properties to all events, including current page information, previous page location, and page type classification.
To disable page URL enrichment, set autocapture.pageUrlEnrichment to false:
amplitude.init(API_KEY, {
autocapture: {
pageUrlEnrichment: false,
},
});
For custom configuration or if you disabled autocapture entirely, you can still add the plugin manually:
import { pageUrlEnrichmentPlugin } from '@amplitude/plugin-page-url-enrichment-browser';
const pageUrlEnrichment = pageUrlEnrichmentPlugin();
amplitude.add(pageUrlEnrichment);
amplitude.init(API_KEY);
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.
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 your amplitude.init call might not have been triggered in your codebase or you aren't using the correct Amplitude instance during initialization. Therefore, check your implementation."
Use the Inspect > Network tab to view all network requests made by your page. Search for the Amplitude request.
Check the response code and ensure that the response payload is as expected.
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.
The following are common issues specific to Browser SDK. For more general common issues, see SDK Troubleshooting and Debugging.
Ad Blocker might lead to event dropping. The following errors indicate that the tracking has been affected by Ad Blocker. When loading through 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.
Amplitude recommends using a proxy server to avoid this situation.
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. If these values aren't persistent or aren't increasing by one, that could be the reason.
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 isn't 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 of Access-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.
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 to beacon upon page exit. sendBeacon doesn't work in this case because it sends events in the background, and doesn't return server responses like 4xx or 5xx. 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.
You can track anonymous behavior across two different domains. Amplitude identifies anonymous users by their device IDs which must be passed between the domains. To maintain the same session and ensure a continuous user journey, also pass session IDs to the other domain.
v2.8.0 the SDK supports getting the device ID from the URL paramter ampDeviceId. The SDK configuration, for example, init('API_KEY', { deviceId: 'custom-device-id' }) still takes precedence over the URL parameter. Previous versions of the SDK supported the deviceId URL parameter, this option is still supported for backward compatibility but ampDeviceId will take precedence if both are set. You don't need to change your code if upgrade to versions higher than v2.8.0 but it is recommended.For example:
www.example.comwww.example.orgUsers 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.
Starting from v2.8.0, the SDK can automatically get session ID from the URL to keep the same session and ensure a continuous user journey.
getDeviceId() and the session ID from getSessionId().www.example.com?ampDeviceId=device_id_from_site_1&SessionId=1716245958483)init('API_KEY', null).If the deviceId and sessionId aren't set in init('API_KEY', null, { deviceId: 'custom-device-id', sessionId: 1716245958483 }), the SDK automatically falls back to using the URL parameters respectively.
To improve security and prevent the use of stale session or device IDs, you can include an ampTimestamp parameter that acts as an evaluation window. The SDK only uses ampSessionId and ampDeviceId URL parameters if the ampTimestamp value is in the future (greater than the current time).
For example:
www.example.com?ampDeviceId=device_id&SessionId=session_id&Timestamp=1640995500000
When ampTimestamp expires (is less than the current time), the SDK ignores the ampSessionId and ampDeviceId parameters. It falls back to generating new values or using stored values from cookies. If ampTimestamp isn't provided, the SDK behaves as before for backward compatibility.
This feature ensures that cross-domain tracking parameters remain valid only for a limited time window. This prevents potential security issues from long-lived URLs with embedded tracking parameters.
Amplitude recommends that you follow the same session ID format as the Browser SDK using Date.now() because the SDK checks if an event is in session every time it tracks an event. For example:
// if session ID is set to 12345
// https://www.example.com?ampDeviceId=my-device-id&SessionId=12345
amplitude.init(API_KEY)
// session ID is set to 12345 after init()
amplitude.track("event")
// session ID is set back to Date.now()
// because the tracked "event" is not in the previous session 12345
Unlike standard network requests, sendBeacon sends events in the background, even if the user closes the browser or leaves the page.
sendBeacon sends events in the background. As a result, events dispatched by sendBeacon don't return server responses. Keep the following in mind if you use sendBeacon:
sendBeacon may send events in parallel. This can lead to some UTM properties not being set, for example for session start events. In contrast, while using fetch, the SDK waits for responses before proceeding, guaranteeing event order.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,
}
);
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()
},
);
If your web app configures the strict Content Security Policy (CSP) for security concerns, adjust the policy to whitelist the Amplitude domains:
https://*.amplitude.com to script-src.https://*.amplitude.com to connect-src.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.
AMP prefix and the first ten digits of the API key: AMP_{first_ten_digits_API_KEY}.AMP_MKTG and the first ten digits of the API key: AMP_MKTG_{first_ten_digits_API_KEY}.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 the AMP_TEST prefix cookies if, for some reason, they're not successfully deleted.AMP_TLDTEST prefix to find a subdomain that supports cookie storage. For example, when checking for cookie support on https://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 the AMP_TLDTEST prefix cookies if, for some reason, they're not successfully deleted.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.
The SDK creates two types of cookies: user session cookies and marketing campaign cookies.
User session cookies
Description
optOutRequired. A flag to opt this device out of Amplitude tracking. If this flag is set, no additional information will be stored for the user
userIdUpon 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
deviceIdA 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
sessionIdA randomly generated string for each session
lastEventTimeTime of the last event, used to determine when to expire and create a new session Id
lastEventIdId of the last event
Marketing campaign cookies
Description
utm_campaignThis identifies a specific campaign used (for example, "summer_sale")
utm_contentThis identifies what brought the user to the site and is commonly used for A/B testing (for example, "banner-link", "text-link")
utm_idAn optional parameter for tracking unique IDs or transaction IDs associated with the link.
utm_mediumThis identifies a specific campaign used (for example, "summer_sale")
utm_sourceThis identifies which website sent the traffic (for example, Google, Facebook)
utm_termThis identifies paid search terms used (for example, product+analytics)
referrerThe last page the user was on (for example,
https://amplitude.com/behavioral-analytics-platform?ref=nav)
referring_domainThe domain that the user was last on (for example,
https://amplitude.com)
dclidGoogle campaign manager Click Identifier
gbraidGoogle Click Identifier for iOS device from Web to App
gclidGoogle Click Identifier from URL parameters
fbclidFacebook Click Identifier from URL parameters
ko_click_idKochava Click Identifier from URL parameters
msclkidMicrosoft Click Identifier
ttclidTikTok Click Identifier
twclidTwitter Click Identifier from URL parameter
wbraidGoogle Click Identifier for iOS device from App to Web
li_fat_idLinkedIn member indirect identifier for Members for conversion tracking, retargeting, analytics
rdt_cidReddit Click Identifier
Opt-out of using cookies by setting identityStorage to localStorage 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).
amplitude.init("api-key", null, {
identityStorage: "localStorage",
});
config.flushIntervalMillis to a small value like 1 may cause an ERR_NETWORK_CHANGED error.Beginning with version 2.4.0, the Amplitude Browser SDK supports offline mode. The SDK checks network connectivity every time it tracks an event. If the device is connected to network, the SDK schedules a flush. If not, it saves the event to storage. The SDK also listens for changes in network connectivity and schedules a flush of all stored events when the device reconnects, based on the config.flushIntervalMillis setting.
To disable offline mode, add offline: amplitude.Types.OfflineDisabled to the amplitude.init() call as shown below.
amplitude.init(AMPLITUDE_API_KEY, {
offline: amplitude.Types.OfflineDisabled
});
Amplitude tracks marketing attribution and excludes all referrers from subdomains by default. Learn more about exclude referrers. Once you enable marketing attribution tracking, Amplitude generates identify events to assign the campaign values as user properties in specific scenarios. Refer to the following section to learn when Amplitude tracks marketing attribution and updates user properties.
Amplitude tracks changes in marketing attribution in two scenarios: during SDK initialization and event processing.
To debug, you can get the referrer by typing document.referrer in your Browser console and compare it with your config.autocapture.attribution.excludeReferrers. If document.referrer is empty, then it's considered as a direct traffic. You can get the session ID under AMP_{last 10 digits of your API key} on the "Cookies" tab of the Ampitude Chrome extension and get the previous campaign stored under AMP_MKTG_{last 10 digits of your API key}.
For more information, see the scenarios outlined below that demonstrate when Amplitude does or doesn't track marketing attribution. These examples are illustrative, not exhaustive.
Tracking occurs when either of the following applies:
| Rule | Example |
|---|---|
| The current subdomain is not an excluded referrer. | The referrer does not originates from the same domain or the current subdomain is not match any referrer in config.autocapture.attribution.excludeReferrers. |
| No previous campaign. | A user's initial visit. |
| There is an introduction of new UTM parameter or Click ID parameter. | If any utm parameters or Click ID parameters have been dropped during a session, we will unset it. |
| The referrer domain changes to a new one. | Referrer domain changed from a.test.com to b.test-new.com |
Amplitude doesn't track marketing attribution under any of the following conditions:
| Rule | Example |
|---|---|
| The referrer originates from the same domain with default configuration. | The landing page is a.test.com, with the referrer set to b.test.com. |
| A specific referrer domain is explicitly excluded. | When setting config.autocapture.attribution.excludeReferrers = [a.test.com], and the referrer domain is a.test.com for the current page. |
The subdomain is specified or matches the regular expression in config.autocapture.attribution.excludeReferrers. |
Configuration of excludeReferrers involves specific string arrays or a regular expression. |
| The user engages in direct traffic within the same session. | During a session, a user clicks on a link without any campaign attribution parameters, including the absence of UTM and click id parameters from an email. |
| SPA redirect without page reloading | During a session, a user clicks on a link without any campaign attribution parameters, including the absence of UTM and click id parameters from an email. |
SPA typically don't experience a true page load after a visitor enters the site, which means the referrer information doesn't update when clicking internal links. UTM parameters may be dropped during SPA redirects, while the referrer remains unchanged. This is a known issue in the industry. To address this problem, you can either:
Beginning with version 2.10.0, the Amplitude Browser SDK supports remote configuration. By default, the SDK disables this feature.
Autocapture supports remote configuration options for tracking default events. When you enable this setting, the remote configuration overrides your client-side configuration. Find the remote configuration options in Data > Settings > Autocapture.
To enable remote config, add fetchRemoteConfig: true to the amplitude.init() call as shown below.
amplitude.init(AMPLITUDE_API_KEY, {
fetchRemoteConfig: true
});
In Amplitude, navigate to Data > Settings > Autocapture to add or update a remote configuration.
To proxy remote configuration requests through your own server (for example, to bypass ad blockers), configure the remoteConfig option:
amplitude.init(AMPLITUDE_API_KEY, {
remoteConfig: {
serverUrl: 'https://your-proxy.example.com/config'
}
});
When remoteConfig.serverUrl is set, the SDK sends remote configuration requests to your custom URL instead of Amplitude's endpoints. Analytics events still use serverUrl or the default Amplitude endpoints.
fetchRemoteConfig option is deprecated. Use remoteConfig.fetchRemoteConfig instead for new implementations.June 12th, 2025
Need help? Contact Support
Visit Amplitude.com
Have a look at the Amplitude Blog
Learn more at Amplitude Academy
© 2025 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.