What you will learn in this article
This article represents an in-depth guide for installing and using the Amplitude JavaScript SDK. Use this SDK to track users, user properties and event properties.
The SDK automatically pulls useful data from a user's device, including device family, operating system version, and device type. They are displayed as user properties in Amplitude; all other items that require tracking will have to be instrumented, using the guidelines provided in this article.
Prerequisites
Before reading this article, we recommend having a look at the prerequisites list below. The information presented in this list will help out with both useful information and good to know practices but will also contain links to related topics and Help Center articles:
- The variables and values in red are what you will need to replace with your own
- Please see our JavaScript SDK reference for a description of all available SDK methods
- For best practices on instrumenting Amplitude, see our Getting Started Guide for Developers
- The source code for Amplitude's JavaScript SDK can be found on GitHub here
- For additional information regarding SDK installation for Amplitude, please feel free to check out our Developers Centre here
- More detailed information about User Property Definitions here
- To check if your installation of the JS SDK was successful, please feel free to use our Instrumentation Explorer
Table of Contents
- Installation
- Tracking Events
- Tracking Sessions
- Setting Custom User IDs
- Setting Event Properties
- Setting User Properties
- Setting Group Properties
- Tracking Revenue
- Opting User Out of Logging
- Getting the Device ID
- Settings Configuration Options
- RequireJS
- Google Tag Manager
- Cross Domain Tracking
- Advanced
Installation
1. Create an Amplitude account. If you have not already done so, go to https://amplitude.com and register for an account. Then, create an organization and a project. You will immediately receive an API Key for the project you have just created. Our Getting Started Guide can be found here.
2. Install the SDK. There are a few options to install the JavaScript SDK.
- On every page that uses analytics, paste the following JavaScript code between the
<head>
and</head>
tags:
<script type="text/javascript">
(function(e,t){var n=e.amplitude||{_q:[],_iq:{}};var r=t.createElement("script")
;r.type="text/javascript"
;r.integrity="sha384-RsEu4WZflrqYcEacpfoGSib3qaSvdYwT4D+DrWqeBuDarSzjwUQR1jO8gDiXZd0E"
;r.crossOrigin="anonymous";r.async=true
;r.src="https://cdn.amplitude.com/libs/amplitude-6.2.0-min.gz.js"
;r.onload=function(){if(!e.amplitude.runQueuedFunctions){
console.log("[Amplitude] Error: could not load SDK")}}
;var i=t.getElementsByTagName("script")[0];i.parentNode.insertBefore(r,i)
;function s(e,t){e.prototype[t]=function(){
this._q.push([t].concat(Array.prototype.slice.call(arguments,0)));return this}}
var o=function(){this._q=[];return this}
;var a=["add","append","clearAll","prepend","set","setOnce","unset"]
;for(var u=0;u<a.length;u++){s(o,a[u])}n.Identify=o;var c=function(){this._q=[]
;return this}
;var l=["setProductId","setQuantity","setPrice","setRevenueType","setEventProperties"]
;for(var p=0;p<l.length;p++){s(c,l[p])}n.Revenue=c
;var d=["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain","setDeviceId","enableTracking","setGlobalUserProperties","identify","clearUserProperties","setGroup","logRevenueV2","regenerateDeviceId","groupIdentify","onInit","logEventWithTimestamp","logEventWithGroups","setSessionId","resetSessionId"]
;function v(e){function t(t){e[t]=function(){
e._q.push([t].concat(Array.prototype.slice.call(arguments,0)))}}
for(var n=0;n<d.length;n++){t(d[n])}}v(n);n.getInstance=function(e){
e=(!e||e.length===0?"$default_instance":e).toLowerCase()
;if(!n._iq.hasOwnProperty(e)){n._iq[e]={_q:[]};v(n._iq[e])}return n._iq[e]}
;e.amplitude=n})(window,document);
amplitude.getInstance().init("API_KEY");
</script>
- If you are using
npm
, use the following command:
npm install amplitude-js
- If you are using
bower
, use the following command:
bower install amplitude-js
3. Insert your API Key. Replace API_KEY
with the API Key given to you. You can find your project's API Key in your project's Settings page.
4. Start tracking events. Data is sent to Amplitude via events. As a result, you will have to explicitly log events in order to see any data in your project. To track an event anywhere on the page, call:
amplitude.getInstance().logEvent('EVENT_TYPE');
where EVENT_TYPE
is the name you are giving to the event you want to track.
5. Event uploads. Events are uploaded immediately and saved to the browser's local storage until the server confirms the upload. After calling logEvent
in your app, you will immediately see data appear in Amplitude.
6. Configure the SDK. You can configure Amplitude via the SDK configuration options.
Tracking Events
It is important to consider what types of events you care about as a developer. You should aim to track between 20 and 200 types of events on your site. Common event types are actions the user initiates (such as pressing a button) and events you want the user to complete (such as filling out a form, completing a level, or making a payment).
Here are some resources to help you with your taxonomy or instrumentation planning:
Having a large number of distinct event types, event properties, and user properties can make data exploration and visualization very confusing. By default, we only show the first:
- 2000 distinct event types
- 2000 distinct event properties
- 1000 distinct user properties
Anything past the above thresholds will not be visualized. Note: The raw data is not impacted by this in any way, meaning that you will still see the values in the raw data but they will not be visualized in the platform. A single call to logEvent
should not have more than 1000 event properties. Likewise, a single call to setUserProperties
should not have more than 1000 user properties. If the 1000 property limit is exceeded then the properties will be dropped and a warning will be printed in the console. We have put in very conservative estimates for the event type and property caps that we do not expect to be exceeded in any practical use case. If you feel that your use case will go above those limits please reach out to us here.
To track an event anywhere on the page, call:
amplitude.getInstance().logEvent('EVENT_TYPE');
where EVENT_TYPE
is the name you are giving to the event you want to track.
Backwards Compatibility
Version 3.0.0 (released in May 2016) was a major update that brought support for logging events to multiple Amplitude projects (multiple API keys).
Important Note:
- This change is not 100% backwards compatible and may break on your setup so be sure to see the subsection below "Things That Will Break" if you are updating from a version before 3.0.0.
The amplitude
object now maintains one or more instances, and each instance has a separate apiKey
, userId
, deviceId
, and settings. Having separate instances allows for the logging of events to separate Amplitude projects. The most important API change is how you interact with the amplitude
object. Before v3.0.0, you would directly call amplitude.logEvent('EVENT_TYPE')
. Now, the preferred way is to call functions on an instance as follows:
amplitude.getInstance('INSTANCE_NAME').logEvent('EVENT_TYPE')
Most people upgrading to v3.0.0 will continue logging events to a single Amplitude project. To make this transition as smooth as possible, we try to maintain backwards compatibility for most things by having a default instance which you can fetch by calling amplitude.getInstance()
with no instance name. The code examples in this article will follow this use case. All of the existing event data, existing settings, and returning users (users who already have a deviceId
and/or userId
) will stay with the default instance. You should initialize the default instance with your existing apiKey
. All of the public methods of amplitude
should still work as expected because they have all been mapped to their equivalent on the default instance. For example, amplitude.init('API_KEY')
should still work as it has been mapped to:
amplitude.getInstance().init('API_KEY')
Likewise, amplitude.logEvent('EVENT_TYPE')
should still work as it has been mapped to:
amplitude.getInstance().logEvent('EVENT_TYPE')
amplitude.options
will still work and will map to amplitude.getInstance().options
if, for example, you were using it to access the deviceId
.
To confirm that the instance has been properly initialized, you can use our onInit
callback to fire a function after the SDK is initialized.
AmplitudeClient.prototype.onInit = function (callback) {
if (this._isInitialized) {
callback();
} else {
this._onInit.push(callback);
}
};
Things That Will Break
If you were accessing private properties on the amplitude
object, those will no longer work (e.g. amplitude._sessionId
or amplitude._eventId
). You will need to update those references to fetch from the default instance (e.g. amplitude.getInstance()._sessionId
or amplitude.getInstance()._eventId
).
Logging Events to a Single Project (Preferred Method)
If you want to log events to a single Amplitude project (and a single API key), then you should call functions on the default instance. You can fetch this by calling amplitude.getInstance()
with no instance name. Here is an example:
amplitude.getInstance().init('API_KEY'); amplitude.getInstance().logEvent('EVENT_TYPE');
You can also assign instances to a variable and call functions on that variable:
var project = amplitude.getInstance(); project.init('API_KEY'); project.logEvent('EVENT_TYPE');
Logging Events to Multiple Projects
If you want to log events to multiple Amplitude projects, then you will need to have separate instances for each Amplitude project. As mentioned earlier, each instance will allow for completely independent apiKeys
, userIds
, deviceIds
, and settings.
You will need to assign a name to each Amplitude project/instance and use that name consistently when fetching that instance to call functions.
Important Note:
- Once you have chosen a name for that instance you cannot change it. Choose your instance names wisely. Every instance's data and settings are tied to its name. You will need to continue using that instance for all future versions of your project to maintain data continuity.
These names do not need to be the names of your projects in the Amplitude platform, but they will need to remain consistent throughout your code. You also need to be sure that each instance is initialized with the correct apiKey
.
Instance names must be non-null and non-empty strings. Names are case insensitive, and you can fetch each instance name by calling amplitude.getInstance('INSTANCE_NAME')
. As mentioned before, each new instance created will have its own apiKey
, userId
, deviceId
, and settings.
Important Note:
- You will have to reconfigure all the settings for each instance.
This gives you the freedom to have different settings for each instance. The following is an example of how to set up and log events to two separate projects:
amplitude.getInstance().init('12345', null, {batchEvents: true}); // existing project, existing settings, and existing API key
amplitude.getInstance('new_project').init('67890', null, {includeReferrer: true}); // new project, new API key
amplitude.getInstance('new_project').setUserId('joe@gmail.com'); // need to reconfigure new project
amplitude.getInstance('new_project').setUserProperties({'gender':'male'});
amplitude.getInstance('new_project').logEvent('Clicked');
var identify = new amplitude.Identify().add('karma', 1);
amplitude.getInstance().identify(identify);
amplitude.getInstance().logEvent('Viewed Home Page');
As mentioned before, each instance will have its own deviceId
. If you want your projects to share the same deviceId
, you can do so after init
by fetching the deviceId
and using setDeviceId
. Here is an example of how to copy the existing deviceId
to the new_project
instance:
var deviceId = amplitude.getInstance().options.deviceId; // existing deviceId
amplitude.getInstance('new_project').setDeviceId(deviceId); // transferring existing deviceId to new_project
Tracking Sessions
Events triggered within 30 minutes of each other are counted towards the current session. The time of the first event marks the start time of a session and the last event triggered marks the end time of a session. You can change the session timeout window via the SDK configuration option sessionTimeout
.
Getting the Session ID
You can use the helper method _sessionId
to get the value of the current sessionId
:
var sessionId = amplitude.getInstance()._sessionId;
Setting Custom User IDs
If your app has its own login system that you want to track users with, you can call setUserId
at any time:
amplitude.getInstance().setUserId('USER_ID');
You can also add the User ID as an argument to the init
call:
amplitude.getInstance().init('API_KEY', 'USER_ID');
You should not assign users a User ID that could change as each unique User ID is interpreted as a unique user in Amplitude. Please see our article on how we identify and count unique users for further information.
Logging Out and Anonymous Users
A user's data will be merged on the backend so that any events up to that point from the same browser will be tracked under the same user. If a user logs out or you want to log events under an anonymous user, you will need to do:
- Set the
userId
tonull
. - Regenerate a new
deviceId
.
After doing that, events coming from the current user will appear as a brand new user in Amplitude. Note that if you choose to do this, then you will not be able to see that the two users were using the same browser/device. Here is an example:
amplitude.getInstance().setUserId(null); // not string 'null' amplitude.getInstance().regenerateDeviceId();
Setting Event Properties
You can send event property attributes to any event by passing a JavaScript object as the second argument to logEvent
. The JavaScript object should be in the form of key + value pairs that can be JSON serialized. The keys should be strings but the values can be booleans, strings, numbers, arrays of strings/numbers/booleans, nested JavaScript objects, or errors (note that you cannot nest arrays or JavaScript objects inside array values). The SDK will validate the event properties that you set and will log any errors or warnings to console if there are any issues. Here is an example:
var eventProperties = {};
eventProperties.key = 'value';
amplitude.getInstance().logEvent('EVENT_TYPE', eventProperties);
Alternatively, you can set multiple event properties like this:
var eventProperties = {
'color': 'blue',
'age': 20,
'key': 'value'
};
amplitude.getInstance().logEvent('EVENT_TYPE', eventProperties);
Arrays in Event Properties
The SDK supports arrays in event properties. Here is an example:
var colors = ['rose', 'gold']; var eventProperties = {'colors': colors}; amplitude.getInstance().logEvent('Purchase iPhone', eventProperties);
Setting User Properties
Important Note:
- Please be sure to not track data that may be against your privacy terms..
The SDK automatically pulls useful data about the browser, including browser type and operating system version. They are displayed as user properties in Amplitude. You can read more about them here. You can turn off this automatic tracking by specifying which user properties you want tracked in the SDK's configuration options.
The SDK supports the operations set
, setOnce
, unset
, and add
on individual user properties. The operations are declared via a provided Identify
interface. Multiple operations can be chained together in a single Identify
object. The Identify
object is then passed to the Amplitude client to send to the server. The results of the operations will be visible immediately in the dashboard and will take effect for events logged after.
set
: This sets the value of a user property.var identify = new amplitude.Identify().set('gender', 'female').set('age', 20);
amplitude.getInstance().identify(identify);setOnce
: This sets the value of a user property only once. SubsequentsetOnce
operations on that user property will be ignored. In the following example, 'sign_up_date' will be set once to '2015-08-24', and the followingsetOnce
to '2015-09-14' will be ignored. NOTE: Initial setOnce value can change if there are merged users.var identify = new amplitude.Identify().setOnce('sign_up_date', '2015-08-24'); amplitude.getInstance().identify(identify);
var identify = new amplitude.Identify().setOnce('sign_up_date', '2015-09-14'); amplitude.getInstance().identify(identify);unset
: This will unset and remove a user property.var identify = new amplitude.Identify().unset('gender').unset('age'); amplitude.getInstance().identify(identify);
add
: This will increment a user property by some numerical value. If the user property does not have a value set yet, it will be initialized to 0 before being incremented.var identify = new amplitude.Identify().add('karma', 1).add('friends', 1); amplitude.getInstance().identify(identify);
append
: This will append a value or values to a user property array. If the user property does not have a value set yet, it will be initialized to an empty list before the new values are appended. If the user property has an existing value and it is not a list, it will be converted into a list with the new value appended.var identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']); amplitude.getInstance().identify(identify);
prepend
: This will prepend a value or values to a user property. Prepend means inserting the value(s) at the front of a given list. If the user property does not have a value set yet, it will be initialized to an empty list before the new values are prepended. If the user property has an existing value and it is not a list, it will be converted into a list with the new value prepended.var identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']); amplitude.getInstance().identify(identify);
Important Note:
- If a user property is used in multiple operations on the same Identify object, then only the first operation will be saved and the rest will be ignored.
In this example, only the set
operation will be saved and the add
and the unset
will be ignored:
var identify = new amplitude.Identify()
.set('karma', 10)
.add('karma', 1)
.unset('karma');
amplitude.getInstance().identify(identify);
Arrays in User Properties
The SDK supports arrays in user properties. Any of the user property operations above (with the exception of add
) can accept a JSONArray. You can directly set
arrays or use append
to generate an array.
var identify = new amplitude.Identify() .set('colors', ['rose', 'gold']) .append('ab-tests', 'campaign_a') .append('existing_list', [4, 5]); amplitude.getInstance().identify(identify);
Setting Multiple User Properties
You may use setUserProperties
shorthand to set multiple user properties at once. This method is simply a wrapper around Identify.set
and identify
.
var userProperties = {
gender: 'female',
age: 20
};
amplitude.getInstance().setUserProperties(userProperties);
Clearing User Properties
You may use clearUserProperties
to clear all user properties at once. This will wipe all of the current user's user properties. Note: The result is irreversible! Amplitude will not be able to sync the user's user property values before the wipe to any future events that the user triggers as they will have been reset.
amplitude.getInstance().clearUserProperties();
Setting Group Properties
Just like setting user properties, you can also use Identify interface to set and update group properties.
var groupIdentify = new amplitude.Identify().set('members', 80);
amplitude.getInstance().groupIdentify('company', 'Amplitude', groupIdentify);
Tracking Revenue
The preferred method of tracking revenue for a user is to use logRevenueV2()
in conjunction with the provided Revenue
interface. Revenue
instances will store each revenue transaction and allow you to define several special revenue properties (such as revenueType
, productId
, etc.) that are used in Amplitude. The three required revenue properties are productId
, quantity
, and price
. You can also add event properties to the revenue event via the eventProperties
field. These Revenue
instance objects are then passed into logRevenueV2
to send as revenue events to Amplitude's servers. This allows us to automatically display data relevant to revenue in the platform.
Calling logRevenueV2
will generate to 2 different event types in the platform:
- '[Amplitude] Revenue': This event is logged for all revenue events.
- '[Amplitude] Revenue (Unverified)': This revenue event will contain the actual '$revenue' property.
You cannot change the default names given to these client-side revenue events in the raw data but you do have the option to modify the display name. To learn more about tracking revenue, see our documentation here.
Important Note:
- Amplitude currently does not support currency conversion. All revenue data should be normalized to your currency of choice before being sent to Amplitude.
Each time a user generates revenue, you should create a Revenue
object and fill out the revenue properties:
var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); amplitude.getInstance().logRevenueV2(revenue);
Each revenue event has fields available, and each field has a corresponding set
method (for example, setProductId
, setQuantity
, etc.). This table describes the different fields:
Name | Type | Description | Default |
---|---|---|---|
(optional) |
string | An identifier for the product. We recommend something like the Google Play Store product ID. | null |
(required) |
integer |
The quantity of products purchased. Note: revenue = |
1 |
(required) |
double |
The price of the products purchased, and this can be negative. Note: revenue = |
null |
(optional) |
string | The type of revenue (e.g. tax, refund, income). | null |
(optional) |
object | An object of event properties to include in the revenue event. | null |
Important Note:
- The price can be negative, which might be useful for tracking revenue lost (e.g. refunds or costs). You can also set event properties on the revenue event just as you would with logEvent by passing in an object of string key + value pairs. However, these event properties will only appear in the Event Segmentation chart and not in the Revenue Analysis or Revenue LTV chart types.
Backwards Compatibility
The existing logRevenue
methods still work but are deprecated. Fields such as revenueType
will be missing from events logged with the old methods so segmentation on those events will be limited.
Opting User Out of Logging
You can turn off logging for a given user by calling setOptOut
:
amplitude.getInstance().setOptOut(true);
No events will be saved or sent to the server while this is enabled. The opt out setting will persist across page loads. You can reenable logging by calling:
amplitude.getInstance().setOptOut(false);
Getting the Device ID
You can get a user's current Device ID with the following code:
var deviceId = amplitude.getInstance().options.deviceId; // existing deviceId
Settings Configuration Options
You can configure Amplitude by passing an object as the third argument to the init
:
amplitude.getInstance().init("API_KEY", null, { // optional configuration options saveEvents: true, includeUtm: true, includeReferrer: true,
trackingOptions: {
city: false,
ip_address: false,
} });
- The trackingOptions configurations will only prevent default properties from being tracked on newly created projects, where data has not yet been sent. Please contact our Support team at support.amplitude.com if you would like default properties blocked (moving forward) on projects with existing data.
Note: This only works if includeReferrer
or includeUtm
includeUtm are set to true.
Option | Description | Default |
---|---|---|
boolean |
If true , then events are batched together and uploaded only when the number of unsent events is greater than or equal to eventUploadThreshold or after eventUploadPeriodMillis milliseconds have passed since the first unsent event was logged. |
false |
number |
The number of days after which the Amplitude cookie will expire. |
(10 years) |
boolean |
If true, the SDK will not write any cookies and will attempt to use localStorage instead. Note: This will prevent you from tracking users across different subdomains of your site. |
false |
string |
The custom Device ID to set. Note: This is not recommended unless you know what you are doing (e.g. you have your own system for tracking user devices). |
A randomly generated UUID. |
boolean |
If true , then the SDK will parse Device ID values from the URL parameter amp_device_id if available. Device IDs defined in the configuration options during init will take priority over Device IDs from URL parameters. |
null |
string |
Set a custom domain for the Amplitude cookie. To include subdomains, add a preceding period, eg: ('.amplitude.com) |
The top domain of the current page's URL. ('amplitude.com') |
number |
Amount of time in milliseconds that the SDK waits before uploading events if batchEvents is true . |
(30 sec) |
number |
Minimum number of events to batch together per request if batchEvents is true . |
30 |
boolean |
If true , the events will always be uploaded to HTTPS endpoint. Otherwise, it will use the embedding site's protocol. |
true |
boolean |
If true , the cookies will be secured. |
false |
string |
Sets the SameSite attribute on the amplitude cookie. |
'None' |
boolean |
If true , captures the gclid URL parameter as well as the user's initial_gclid via a setOnce operation. |
false |
boolean |
If true , captures the referrer and referring_domain for each session, as well as the user's initial_referrer and initial_referring_domain via a setOnce operation. |
false |
boolean |
If true , finds UTM parameters in the query string or the _utmz cookie, parses, and includes them as user properties on all events uploaded. This also captures initial UTM parameters for each session via a setOnce operation. |
false |
string |
Custom language to set. | The language determined by the browser. |
string |
Level of logs to be printed in the developer console. Valid values are 'DISABLE' , 'ERROR' , 'WARN' , 'INFO' . To learn more about the different options, see the Advanced section. |
'WARN' |
boolean |
Whether or not to disable tracking for the current user. | false |
string |
The custom platform to set. | 'Web' |
boolean |
If Note: Without saving events, events may be lost if the user navigates to another page before the events are uploaded. |
true |
number |
Maximum number of events to save in localStorage . If more events are logged while offline, then old events are removed. |
1000 |
boolean |
If true , then includeGclid , includeReferrer , and includeUtm will only track their respective properties once per session. New values that come in during the middle of the user's session will be ignored. Set to false to always capture new values. |
true |
number |
The time between logged events before a new session starts in milliseconds. |
(30 min) |
object |
By default the JS SDK tracks various user properties such as city and country. You can disable the tracking of specific fields by passing in an object for trackingOptions that maps the field name to false .Note: JS SDK does not collect advertising IDs by default. You will need to send these using HTTP API V2. This option will also only affect new projects where data hasn't been sent yet. If you want to remove default properties off of an existing project, please reach out to Support at support.amplitude.com |
{ |
boolean |
If If set to Note: This only works if |
false |
number |
The maximum number of events to send to the server per request. | 100 |
RequireJS
If you are using RequireJS to load your JavaScript files, then you can also use it to load the Amplitude JavaScript SDK script directly instead of using our loading snippet. On every page that uses analytics, paste the following JavaScript code between the <head>
and </head>
tags:
<script src='scripts/require.js'></script> <!-- loading RequireJS -->
<script>
require(['https://cdn.amplitude.com/libs/amplitude-5.11.0-min.gz.js'], function(amplitude) {
amplitude.getInstance().init('API_KEY'); // replace API_KEY with your Amplitude API key.
window.amplitude = amplitude; // You can bind the amplitude object to window if you want to use it directly.
amplitude.getInstance().logEvent('Clicked Link A');
});
</script>
You can also define the path in your RequireJS configuration like this:
<script src='scripts/require.js'></script> <!-- loading RequireJS -->
<script>
requirejs.config({
paths: {
'amplitude': 'https://cdn.amplitude.com/libs/amplitude-5.11.0-min.gz.js'
}
});
require(['amplitude'], function(amplitude) {
amplitude.getInstance().init('API_KEY'); // replace API_KEY with your Amplitude API key.
window.amplitude = amplitude; // You can bind the amplitude object to window if you want to use it directly.
amplitude.getInstance().logEvent('Clicked Link A');
});
</script>
<script>
require(['amplitude'], function(amplitude) {
amplitude.getInstance().logEvent('Page loaded');
});
</script>
Google Tag Manager
Amplitude's JavaScript SDK supports integration with Google Tag Manager. Take a look at the Send Data to Amplitude via GTM for instructions on how to set it up.
Cross Domain Tracking
You can track anonymous behavior across two different domains. For example, let's say you have the following two domains:
- Site 1: https://www.landingpage.com
- Site 2: https://www.productpage.com
If you want to track an anonymous user who starts on Site 1 and navigates to Site 2, then you will need to pass the Device ID from Site 1 as a parameter to Site 2. After that, you will need to reinitialize the SDK with the passed Device ID. It would look something like:
- From Site 1, grab the Device ID from
amplitude.options.deviceId
. - Pass the Device ID to Site 2 via a URL parameter or third party cookie.
- Initialize the Amplitude SDK on Site 2 with
amplitude.init('API_KEY', null, {deviceId: '$DEVICE_ID'})
.
Advanced
Tracking UTM Parameters, Referrer, and gclid
Amplitude supports automatically tracking:
- Standard UTM parameters from the user's cookie or URL parameters when the configuration option
includeUtm
is set totrue
during initialization. - The referring URL when the configuration option
includeReferrer
is set totrue
during initialization. - gclid (Google Click ID) from URL parameters when the configuration option
includeGclid
is set totrue
during initialization.
If tracking is enabled, then the SDK will set the values as user properties (e.g. referrer
or utm_source
) once per session (this is last touch attribution). The SDK will also save the initial values using a setOnce
operation (e.g. initial_referrer
or initial_utm_source
), and once set that value will never change (this is first touch attribution).
- By default, the SDK will only save the values at the start of the session.
For example, if a user lands on your site with an initial set of UTM parameters and triggers some flow that causes them to land on your site again with a different set of UTM parameters within the same Amplitude session, then that second set will not be saved. You can set the configuration option saveParamsReferrerOncePerSession
to false
to remove that restriction so that the SDK will always capture any new values from the user.
- By default, the SDK will carry over existing values at the start of a new session. To reset those values to null upon instantiating a new session, set unsetParamsReferrerOnNewSession to true.
Setting User Groups
- This feature is only available for Enterprise customers who have purchased the Accounts add-on.
Amplitude supports assigning users to groups and performing queries such as Count by Distinct on those groups. An example would be if you want to group your users based on what organization they are in by using an 'orgId'. You can designate Joe to be in 'orgId' '10' while Sue is in 'orgId' '15'. When performing a query in our Event Segmentation chart, you can then select "..performed by" 'orgId' to query the number of different organizations that have performed a specific event. As long as at least one member of that group has performed the specific event, that group will be included in the count.
When setting groups, you will need to define a groupType
and groupName
(s). In the above example, 'orgId' is the groupType
and the values '10' and '15' are groupName
(s). Another example of a groupType
could be 'sport' with groupName
(s) like 'tennis' and 'baseball'. You can use setGroup(groupType, groupName)
to designate which groups a user belongs to. Note: This will also set the 'groupType:groupName' as a user property. This will overwrite any existing groupName
value set for that user's groupType
, as well as the corresponding user property value. groupType
is a string and groupName
can be either a string or an array of strings to indicate a user being in multiple groups (for example, if Joe is in 'orgId' '10' and '16', then the groupName
would be '[10, 16]'). Here is what your code might look like:
amplitude.getInstance().setGroup('orgId', '15'); amplitude.getInstance().setGroup('sport', ['soccer', 'tennis']);
You can also use logEventWithGroups
to set event-level groups, meaning the group designation only applies for the specific event being logged and does not persist on the user unless you explicitly set it with setGroup
:
var eventProperties = { 'key': 'value' } amplitude.getInstance().logEventWithGroups('initialize_game', eventProperties, {'sport': 'soccer'});
Setting Version Name
By default, no version name is set. You can specify a version name to distinguish between different versions of your site by calling setVersionName
:
amplitude.getInstance().setVersionName('VERSION_NAME');
Setting Date Values
Amplitude compares dates as strings, so it is recommended to use the ISO 8601 format (YYYY-MM-DDTHH:mm:ss), which will allow you to perform date comparisons in the platform (e.g. '2016-01-31' > '2016-01-01'). This will also work for datetime values (e.g. '2017-08-07T10:09:08' > '2017-08-07T01:07:00').
Custom Device IDs
Device IDs are generated randomly, although you can define a custom Device ID by setting it as a configuration option or by calling:
amplitude.getInstance().setDeviceId('DEVICE_ID');
Note: This is not recommended unless you know what you are doing (like if you have your own system for tracking user devices). Make sure the deviceId
you set is sufficiently unique in order to prevent conflicts with other devices in our system. We recommend something like a UUID; see here for an example of how to generate.
Callbacks for logEvent
, Identify
, and Redirect
You can pass a callback function to logEvent
and identify
, which will get called after receiving a response from the server. This is useful if timing may cause an event to not be captured before the browser navigates away from a webpage. Putting the navigation in a callback to the logEvent
method will guarantee the event is captured before the navigation occurs. Here is a logEvent
example:
amplitude.getInstance().logEvent("EVENT_TYPE", null, callback_function);
Here is an identify
example:
var identify = new amplitude.Identify().set('key', 'value'); amplitude.getInstance().identify(identify, callback_function);
The status and response body from the server are passed to the callback function, which you might find useful. Here is an example of a callback function which redirects the browser to another site after a response:
var callback_function = function(status, response) { if (status === 200 && response === 'success') { // do something here } window.location.replace('URL_OF_OTHER_SITE'); };
You can also use this to track outbound links to your website. For example, you would have a link like this:
<a href="javascript:trackClickLinkA();">Link A</a>
Then, you would define a function that is called when the link is clicked like this:
var trackClickLinkA = function() { amplitude.getInstance().logEvent('Clicked Link A', null, function() { window.location='LINK_A_URL'; }); };
In the case that optOut
is true
, then no event will be logged but the callback will be called. In the case that batchEvents
is true
, if the batch requirements eventUploadThreshold
and eventUploadPeriodMillis
are not met when logEvent
is called, then no request is sent but the callback is still called. In these cases, the callback will be called with an input status of 0 and a response of 'No request sent'
.
init
Callbacks
You can also pass a callback function to init
, which will get called after the SDK finishes its asynchronous loading. Note: The instance is passed as an argument to the callback:
amplitude.getInstance().init('API_KEY', 'USER_ID', null, function(instance) { console.log(instance.options.deviceId); // access Amplitude's deviceId after initialization });
Log Level
The logLevel
configuration option allows you to set the level of logs printed to be printed in the developer console. The different levels are as follows:
'INFO'
: This option will show error messages, warnings, and informative messages that may be useful for debugging.'WARN'
: This option will show error messages and warnings. This level will log issues that might be a problem and cause some oddities in the data. For example, this level would display a warning for properties withnull
values.'ERROR'
: This option will show error messages only.'DISABLE'
: This will suppress all log messages.