The Amp Devcenter Test Developer Hub

Welcome to the Amp Devcenter Test developer hub. You'll find comprehensive guides and documentation to help you start working with Amp Devcenter Test as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    

JavaScript

npm versionnpm version

SDK Installation

Installing Via the Snippet

You can install the JavaScript SDK using a small snippet of code which you paste on your site to asynchronously load the SDK. On every page that you want to install Amplitude analytics, paste the code snippet just before the </head> tag, replacing API_KEY with the API Key given to you. You can find your project's API Key in your project's Settings page.

<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-u0hlTAJ1tNefeBKwiBNwB4CkHZ1ck4ajx/pKmwWtc+IufKJiCQZ+WjJIi+7C6Ntm"
;r.crossOrigin="anonymous";r.async=true
;r.src="https://cdn.amplitude.com/libs/amplitude-8.1.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","preInsert","postInsert","remove"]
;for(var c=0;c<a.length;c++){s(o,a[c])}n.Identify=o;var u=function(){this._q=[]
;return this}
;var l=["setProductId","setQuantity","setPrice","setRevenueType","setEventProperties"]
;for(var p=0;p<l.length;p++){s(u,l[p])}n.Revenue=u
;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(!Object.prototype.hasOwnProperty.call(n._iq,e)){n._iq[e]={_q:[]};v(n._iq[e])
}return n._iq[e]};e.amplitude=n})(window,document);

amplitude.getInstance().init("API_KEY");
</script>

Installing with npm or yarn

Alternatively, you can install the npm module and embed the SDK directly into your product.
If you are using npm, use the following command:

npm install amplitude-js

If you are using yarn, use the following command:

yarn add amplitude-js

You will now be able to import amplitude in your project:

import amplitude from 'amplitude-js';

Usage & Examples

Initialization

Initialization is necessary before any instrumentation is done. The API key for your Amplitude project is required. The default instance will be created by default, but several instances can be maintained if created through getInstance with a string name.

var instance1 = amplitude.getInstance().init("API_KEY"); // initializes default instance of Amplitude client
var instance2 = amplitude.getInstance("instance").init("API_KEY"); // initializes named instance of Amplitude client

Initialization with Options

Custom options can be passed into the init method. A list of all possible options for the client can be found here.

var options = {};
var instance = amplitude.getInstance("instance").init("API_KEY", null, options); // initializes with the given options

Setting User Id

The User ID can be set either upon initializing the client, or after initialization with the setUserId method.

var userId = "12345";
amplitude.getInstance().init("API_KEY", userId); // initializes client with the given userId
var userId = "12345";
amplitude.getInstance().setUserId(userId);

Sending Events

Basic Events

Events represent how users interact with your application. For example, “Button Clicked” may be an action you want to note.

var event = “Button Clicked”;
amplitude.getInstance().logEvent(event);

Events with Properties

Events can also contain properties. They provide context about the event taken. For example, “hover time” may be a relevant event property to “Button Clicked”.

var event = “Button Clicked”;
var eventProperties = {
    "hover time": "100ms"
};
amplitude.getInstance().logEvent(event, eventProperties);

User Properties

User properties help you understand your users at the time they performed some action within your app such as their device details, their preferences, or language.

Setting a User Property

The amplitude Identify object provides controls over setting user properties. An Identify object must first be instantiated, then Identify methods can be called on it, and finally the client will make a call with the Identify object

new amplitude.Identify(); // does nothing, must call one of the following methods and pass to client

var identify = new amplitude.Identify();
amplitude.getInstance().identify(identify); // makes identify call to amplitude with the properties of the identify object

set

set sets the value of a user property. You can also chain together multiple set calls.

var identify1 = new amplitude.Identify().set('key1', 'value1');
var identify2 = new amplitude.Identify().set('key2', 'value2').set('key3', 'value3');
amplitude.getInstance().identify(identify1);
amplitude.getInstance().identify(identify2);

setOnce

setOnce sets the value of a user property only once. Subsequent calls using setOnce will be ignored.

var identify = new amplitude.Identify().setOnce('key1', 'value1');
amplitude.getInstance().identify(identify);

add

add increments 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('value1', 10);
amplitude.getInstance().identify(identify);

Setting Multiple User Properties

You can use setUserProperties as a shorthand to set multiple user properties at once. This method is simply a wrapper around Identify.set and identify. For example, a user's city can be set with the following code.

var userProperties = {
    city: "San Francisco"
};
amplitude.getInstance().setUserProperties(userProperties);

Arrays in User Properties

Arrays can be used as user properties. You can directly set arrays or use append to generate an array.

var values = ['value1', 'value2'];
var identify = new amplitude.Identify().set('key1', values);
amplitude.getInstance().identify(identify);

prepend/append

  • append will append a value or values to a user property array.
  • prepend will prepend a value or values to a user property.

If the user property does not have a value set yet, it will be initialized to an empty list before the new values are added. 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 added.

Disable Tracking

By default, the JS SDK will track a number of properties automatically. You can override this behavior by passing an object called trackingOptions when initializing the SDK, setting the appropriate options to false. These options are listed below:

ParameterDefault Value
citytrue
countrytrue
carriertrue
device_manufacturertrue
device_modeltrue
dmatrue
ip_addresstrue
languagetrue
os_nametrue
os_versiontrue
platformtrue
regiontrue
version_nametrue

Setting Custom User ID

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] instance] initializeApiKey:@"API_KEY" userId:@"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.

Log 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 the events under an anonymous user, you will need to:

  1. Set the userId to null.
  2. Regenerate a new deviceId.

After doing that, events coming from the current user/device will appear as a brand new user in Amplitude. Note: If you choose to do this, you will not be able to see that the two users were using the same device.

amplitude.getInstance().setUserId(null); // not string 'null'
amplitude.getInstance().regenerateDeviceId();

Updated 6 days ago


JavaScript


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.