This is the official documentation for the Analytics JavaScript SDK.
Maintenance SDK
This is a maintenance SDK and will only receive bug fixes until deprecation. Upgrade to the latest Browser SDK 2.0 which supports plugins and more.
Install
Install the Analytics JavaScript SDK in your project.
Snippetnpmyarn
Install the JavaScript SDK using a small snippet of code that you paste on your site to asynchronously load the SDK.
On every page that you want to install analytics, paste the code snippet just before the tag, replacing AMPLITUDE_API_KEY with your project’s API key.
You can find your project’s API Key in your project’s Settings page.
1<script type=“text/javascript“>
2(function(e,t){var n=e.amplitude||{_q:[],_iq:{}};var r=t.createElement(“script“)
3r.type=“text/javascript“;
4r.integrity=“sha384-5fhzC8Xw3m+x5cBag4AMKRdf900vw3AoaLty2vYfcKIX1iEsYRHZF4RLXIsu2o+F“
5r.crossOrigin=“anonymous“;r.async=true;
6r.src=“https://cdn.amplitude.com/libs/amplitude-8.21.4-min.gz.js“;
7r.onload=function(){if(!e.amplitude.runQueuedFunctions){console.log(
8“[] Error: could not load SDK“)}};var s=t.getElementsByTagName(“script“
9)[0];s.parentNode.insertBefore(r,s);function i(e,t){e.prototype[t]=function(){
10this._q.push([t].concat(Array.prototype.slice.call(arguments,0)));return this}}
11var o=function(){this._q=[];return this};var a=[“add“,“append“,“clearAll“,
12“prepend“,“set“,“setOnce“,“unset“,“preInsert“,“postInsert“,“remove“];for(
13var c=0;c<a.length;c++){i(o,a[c])}n.Identify=o;var l=function(){this._q=[];
14return this};var u=[“setProductId“,“setQuantity“,“setPrice“,“setRevenueType“,
15“setEventProperties“];for(var p=0;p<u.length;p++){i(l,u[p])}n.Revenue=l;var d=[
16“init“,“logEvent“,“logRevenue“,“setUserId“,“setUserProperties“,“setOptOut“,
17“setVersionName“,“setDomain“,“setDeviceId“,“enableTracking“,
18“setGlobalUserProperties“,“identify“,“clearUserProperties“,“setGroup“,
19“logRevenueV2“,“regenerateDeviceId“,“groupIdentify“,“onInit“,“onNewSessionStart“
20,“logEventWithTimestamp“,“logEventWithGroups“,“setSessionId“,“resetSessionId“,
21“getDeviceId“,“getUserId“,“setMinTimeBetweenSessionsMillis“,
22“setEventUploadThreshold“,“setUseDynamicConfig“,“setServerZone“,“setServerUrl“,
23“sendEvents“,“setLibrary“,“setTransport“];function v(t){function e(e){t[e
24]=function(){t._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}
25for(var n=0;n<d.length;n++){e(d[n])}}v(n);n.getInstance=function(e){e=(
26!e||e.length===0?“$default_instance“:e).toLowerCase();if(
27!Object.prototype.hasOwnProperty.call(n._iq,e)){n._iq[e]={_q:[]};v(n._iq[e])}
28return n._iq[e]};e.amplitude=n})(window,document);
29
30amplitude.getInstance().init(AMPLITUDE_API_KEY);
31script>
1npm install amplitude-js
1yarn add amplitude-js
You can also install the npm module and embed the SDK directly into your product.
After you’ve installed the SDK, import amplitude into your project.
1import amplitude from ‘amplitude-js‘;
Quickstart
Initialize
Send an event
1// initialize the client
2var instance1 = amplitude.getInstance().init(AMPLITUDE_API_KEY);
1// send an event
2const event = “Button Clicked“;
3amplitude.getInstance().logEvent(event);
Core functions
The following functions make up the core of the Analytics JavaScript SDK.
Initialize
Before you can instrument, you must initialize the SDK using the API key for your project.
Initialization creates a default instance, but you can create more instances using getInstance with a string name.
1var instance1 = amplitude.getInstance().init(“AMPLITUDE_API_KEY“); // initializes default instance of client
2var instance2 = amplitude.getInstance(“instance-name“).init(“AMPLITUDE_API_KEY“); // initializes named instance of client
Initialization with options
Pass custom options in the init method. See a list of options on GitHub.
1var options = {};
2var instance = amplitude.getInstance(“instance“).init(AMPLITUDE_API_KEY, null, options); // initializes with the given options
Configuration
Configuration options
Configure batching behavior
To support high-performance environments, the SDK sends events in batches. Every event logged by logEvent method is queued in memory. Events are flushed in batches in background. You can customize batch behavior with eventUploadThreshold and eventUploadPeriodMillis. By default, the serverUrl will be https://api.amplitude.com. This SDK doesn’t support batch mode, the batch API endpoint.
1amplitude.getInstance().init(apiKey, null, {
2 // Events queued in memory will flush when number of events exceed upload threshold
3 // Default value is 30
4 eventUploadThreshold: 50,
5 // Events queue will flush every certain milliseconds based on setting
6 // Default value is 30000 milliseconds
7 eventUploadPeriodMillis: 100000,
8});
EU data residency
Beginning with version 8.9.0, you can configure the server zone to send data to ‘s EU server after initializing the client.
The server zone configuration supports dynamic configuration as well.
For earlier versions, you need to configure the apiEndpoint property after initializing the client.
Note
For EU data residency, you must initialize the SDK with the API key from EU. Your project must be set up from inside EU.
Version 8.9.0 and higherEarlier versions
1// No need to call setServerUrl for sending data to ‘s EU servers
2amplitude.getInstance().init(euApiKey, null, {
3 serverZone: ‘EU‘,
4 serverZoneBasedApi: true,
5});
1amplitude.getInstance().init(euApiKey, null, {
2apiEndpoint: ‘https://api.eu.amplitude.com‘
3});
Set userID
Set userID when initializing the client, or after initialization with the setUserId method.
Set on initializationSet with setUserId
1var userId = “12345“;
2amplitude.getInstance().init(AMPLITUDE_API_KEY, userId); // initializes client with the given userId
1var userId = “12345“;
2amplitude.getInstance().setUserId(userId);
There is an optional startNewSession parameter for setUserId. Set it to true to start a new user session.
Send events
Basic events
Events represent user interactions with your app. For example, “Button Clicked” may be an action you want to track.
1const event = “Button Clicked“;
2amplitude.getInstance().logEvent(event);
Event properties
Events can have properties that give context about the event. For example, “hover time” is a relevant property for the “Button Clicked” event.
1var event = “Button Clicked“;
2var eventProperties = {
3 “hover time“: “100ms“
4};
5amplitude.getInstance().logEvent(event, eventProperties);
Valid types and limits
Valid data types for event properties are string, array, object, boolean, and number. Object keys have a 1000 character limit.
Arrays in event properties
Event property values can be arrays. You can query array event properties by any subset of the individual properties in the array.
1var event = “Button Clicked“;
2var eventProperties1 = {
3 “selectedColors“: [‘red‘, ‘blue‘]
4};
5amplitude.getInstance().logEvent(event, eventProperties1);
6
7var eventProperties2 = {
8 “selectedColors“: [‘red‘, ‘green‘]
9};
10amplitude.getInstance().logEvent(event, eventProperties2);
User properties
User properties help you understand your users at the time they performed some action within your app. For example, you can learn about their device details, their preferences, or language.
Set a user property
The Identify object provides controls over setting user properties. First, create an Identify object instance, then call Identify methods on it, and then the client makes a call with the Identify object.
1new amplitude.Identify(); // does nothing, must call one of the following methods and pass to client
2
3var identify = new amplitude.Identify();
4amplitude.getInstance().identify(identify); // makes identify call to amplitude with the properties of the identify object
set
Set the value of a user property. You can also chain together several set calls.
1var identify1 = new amplitude.Identify().set(‘key1‘, ‘value1‘);
2var identify2 = new amplitude.Identify().set(‘key2‘, ‘value2‘).set(‘key3‘, ‘value3‘);
3amplitude.getInstance().identify(identify1);
4amplitude.getInstance().identify(identify2);
setOnce
setOnce sets the value of a user property one time. Subsequent calls using setOnce are ignored.
1var identify = new amplitude.Identify().setOnce(‘key1‘, ‘value1‘);
2amplitude.getInstance().identify(identify);
add
Increment a user property by a number with add. If the user property doesn’t have a value set yet, it’s initialized to 0.
1var identify = new amplitude.Identify().add(‘value1‘, 10);
2amplitude.getInstance().identify(identify);
Set multiple user properties
You can use setUserProperties as a shorthand to set multiple user properties at one time.
For example, set a user’s city with this code:
1var userProperties = {
2 city: “San Francisco“
3};
4amplitude.getInstance().setUserProperties(userProperties);
Note
This method is a wrapper around Identify.set and identify.
Arrays in user properties
User properties can be arrays. Directly set arrays or use append to generate an array.
1var values = [‘value1‘, ‘value2‘];
2var identify = new amplitude.Identify().set(‘key1‘, values);
3amplitude.getInstance().identify(identify);
prepend and append
append appends a value or values to a user property array.
prepend 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 adding the new values.
If the user property has an existing value and it’s not a list, it’s converted into a list with the new value added.
User groups
supports assigning users to groups and performing queries, such as Count by Distinct, on those groups. If at least one member of the group has performed the specific event, then the count includes the group.
For example, you want to group your users based on what organization they’re in by using an ‘orgId’. Joe is in ‘orgId’ ’10’, and Sue is in ‘orgId’ ’15’. Sue and Joe both perform a certain event. You can query their organizations in the Event Segmentation Chart.
When setting groups, define a groupType and groupName. In the previous example, ‘orgId’ is the groupType and ’10’ and ’15’ are the values for groupName. Another example of a groupType could be ‘sport’ with groupName values like ‘tennis’ and ‘baseball’.
Setting a group also sets the groupType:groupName as a user property, and overwrites any existing groupName value set for that user’s groupType, and the corresponding user property value. groupType is a string, and groupName can be either a string or an array of strings to indicate that a user is in multiple groups.
Example
If Joe is in ‘orgId’ ’10’ and ’16’, then the groupName would be ‘[“10”, “16”]’. Your code might look like this:
1amplitude.getInstance().setGroup(‘orgId‘, [“10“,“16“]);
You can also use logEventWithGroups to set event-level groups. With event-level groups, the group designation applies only to the specific event being logged, and doesn’t persist on the user unless explicitly
set with setGroup.
1var eventProperties = {
2 ‘key‘: ‘value‘
3}
4
5amplitude.getInstance().logEventWithGroups(‘initialize_game‘, eventProperties, {‘sport‘: ‘soccer‘});
Group identify
Use the Group Identify API to set or update the properties of particular groups. Keep these considerations in mind:
Updates affect only future events, and don’t update historical events.
You…