TypeScript Browser

npm versionnpm version

Our TypeScript Browser SDK lets you send events to our Analytics service.

This library is open-source, please check it out on GitHub.

Getting Started

To get started with using TypeScript Browser SDK, install the package to your project via NPM or script loader.

Installing as Node package

This package is published on NPM registry and is available to be installed using npm and yarn.

# npm 
npm install @amplitude/analytics-browser

# yarn
yarn add @amplitude/analytics-browser

Using script loader

Alternatively, the package is also distributed through a CDN. Copy and paste the script below to your html file.

<script type="text/javascript">
!function(){"use strict";!function(e,t){var r=e.amplitude||{_q:[]};if(r.invoked)e.console&&console.error&&console.error("Amplitude snippet has been loaded.");else{r.invoked=!0;var n=t.createElement("script");n.type="text/javascript",n.integrity="sha384-TeoEVjqxsQrwhskzwWGK6epJC7EkYjvl7k4gmwunKlRBkUK9nT01H4FL9z4VPMSm",n.crossOrigin="anonymous",n.async=!0,n.src="https://cdn.amplitude.com/libs/analytics-browser-0.3.1-min.js.gz",n.onload=function(){e.amplitude.runQueuedFunctions||console.log("[Amplitude] Error: could not load SDK")};var s=t.getElementsByTagName("script")[0];function v(e,t){e.prototype[t]=function(){return this._q.push({name:t,args:Array.prototype.slice.call(arguments,0)}),this}}s.parentNode.insertBefore(n,s);for(var o=function(){return this._q=[],this},i=["add","append","clearAll","prepend","set","setOnce","unset","preInsert","postInsert","remove","getUserProperties"],a=0;a<i.length;a++)v(o,i[a]);r.Identify=o;for(var u=function(){return this._q=[],this},c=["getEventProperties","setProductId","setQuantity","setPrice","setRevenue","setRevenueType","setEventProperties"],p=0;p<c.length;p++)v(u,c[p]);r.Revenue=u;var l=["getDeviceId","setDeviceId","getSessionId","setSessionId","getUserId","setUserId","setOptOut","setTransport"],d=["init","add","remove","track","logEvent","identify","groupIdentify","setGroup","revenue"];function m(e){function t(t,r){e[t]=function(){var n={promise:new Promise((r=>{e._q.push({name:t,args:Array.prototype.slice.call(arguments,0),resolve:r})}))};if(r)return n}}for(var r=0;r<l.length;r++)t(l[r],!1);for(var n=0;n<d.length;n++)t(d[n],!0)}m(r),e.amplitude=r}}(window,document)}();

amplitude.init("YOUR_API_KEY_HERE");
</script>

Usage

Initializing SDK

Initialization is necessary before any instrumentation is done. The API key for your Amplitude project is required. Optionally, a user ID and config object can be passed in this call. The SDK can be used anywhere after it is initialized anywhere in an application.

import { init } from '@amplitude/analytics-browser';

// Option 1, initialize with API_KEY only
init(API_KEY);

// Option 2, initialize including user ID if it's already known
init(API_KEY, '[email protected]');

// Option 2, initialize including configuration
init(API_KEY, '[email protected]', {
  disableCookies: true, // Disables the use of browser cookies
  // More configuration available below.
});

Configuration

The init() function accepts an object to configure the SDK's behavior.

Name

Type

appVersion

string

cookieExpiration

number

cookieSameSite

Lax | String | None

cookieSecure

boolean

cookieStorage

Storage

deviceId

string

disableCookies

boolean

domain

string

flushIntervalMillis

number

flushMaxRetries

number

flushQueueSize

number

includeFbclid

boolean

includeGclid

boolean

includeReferrer

boolean

includeUtm

boolean

logLevel

LogLevel

loggerProvider

Logger

optOut

boolean

partnerId

string

saveEvents

boolean

serverUrl

string

serverZone

ServerZone

sessionId

number

sessionTimeout

number

storageProvider

Storage

trackingOptions

TrackingOptions

transportProvider

Transport

useBatch

boolean

Tracking an Event

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

import { track } from '@amplitude/analytics-browser';

// Track a basic event
track('Button Clicked');

// Track events with optional properties
const eventProperties = {
  buttonColor: 'primary',
};
track('Button Clicked', 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.

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. 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.

🚧

Important Note

If the Identify call is sent after the event, the results of operations will be visible immediately in the dashboard user’s profile area, but it will not appear in chart result until another event is sent after the Identify call. So the identify call only affects events going forward. More details here.

Setting a User Property

The 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.

import { identify, Identify } from '@amplitude/analytics-browser';

const identifyObj = new Identify();
identify(identifyObj);

Identify.set

This method sets the value of a user property. For example, you can set a role property of a user.

import { Identify, identify } from '@amplitude/analytics-browser';

const identifyObj = new Identify();
identifyObj.set('location', 'LAX');

identify(identifyObj);

Identify.setOnce

This method sets the value of a user property only once. Subsequent calls using setOnce() will be ignored. For example, you can set an initial login method for a user and since only the initial value is tracked, setOnce() ignores subsequent calls.

import { Identify, identify } from '@amplitude/analytics-browser';

const identifyObj = new Identify();
identifyObj.setOnce('initial-location', 'SFO');

identify(identifyObj);

Identify.add

This method 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. For example, you can track a user's travel count.

import { Identify, identify } from '@amplitude/analytics-browser';

const identifyObj = new Identify();
identifyObj.add('travel-count', 1);

identify(identifyObj);

Arrays in User Properties

Arrays can be used as user properties. You can directly set arrays or use prepend, append, preInsert and postInsert to generate an array.

Identify.prepend

This method prepends a value or values to a user property array. If the user property does not have a value set yet, it will be initialized to an empty list before the new values are prepended.

import { Identify, identify } from '@amplitude/analytics-browser';

const identifyObj = new Identify();
identifyObj.prepend('visited-locations', 'LAX');

identify(identifyObj);

Identify.append

This method appends 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 prepended.

import { Identify, identify } from '@amplitude/analytics-browser';

const identifyObj = new Identify();
identifyObj.append('visited-locations', 'SFO');

identify(identifyObj);

Identify.preInsert

This method pre-inserts a value or values to a user property, if it does not exist in the user property yet. Pre-insert means inserting the value(s) at the beginning 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 pre-inserted. If the user property has an existing value, it will be no operation.

import { Identify, identify } from '@amplitude/analytics-browser';

const identifyObj = new Identify();
identifyObj.preInsert('unique-locations', 'LAX');

identify(identifyObj);

Identify.postInsert

This method post-inserts a value or values to a user property, if it does not exist in the user property yet. Post-insert means inserting the value(s) at the end 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 post-inserted. If the user property has an existing value, it will be no operation.

import { Identify, identify } from '@amplitude/analytics-browser';

const identifyObj = new Identify();
identifyObj.postInsert('unique-locations', 'SFO');

identify(identifyObj);

Identify.remove

This method removes a value or values to a user property, if it exists in the user property. Remove means remove the existing value(s) from the given list. If the item does not exist in the user property, it will be no operation.

import { Identify, identify } from '@amplitude/analytics-browser';

const identifyObj = new Identify();
identifyObj.remove('unique-locations', 'JFK')

identify(identifyObj);

User Groups

📘

Note: This feature is only available for Growth 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() 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.

import { setGroup } from '@amplitude/analytics-browser';

// set group with single group name
setGroup('orgId', '15');

// set group with multiple group names
setGroup('orgId', ['15', '21']);

Group Properties

📘

This feature is only available to Growth and Enterprise customers who have purchased the Accounts add-on.

Use the Group Identify API to set or update properties of particular groups. However, these updates will only affect events going forward.

The groupIdentify() method accepts a group type and group name string parameter, as well as an Identify object that will be applied to the group.

import { Identify, groupIdentify } from '@amplitude/analytics-browser';

const groupType = 'orgId';
const groupName = '15';
const event = new Identify()
event.set('locale', 'en-us');

groupIdentify(groupType, groupName, identify);

Revenue Tracking

The preferred method of tracking revenue for a user is to use revenue() 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', 'productIdentifier', etc.) 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 allows us to 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. For example, 3 units of a product was purchased at $3.99.

import { Revenue, revenue } from '@amplitude/analytics-browser';

const event = new Revenue()
  .setProductId('com.company.productId')
  .setPrice(3.99)
  .setQuantity(3);

revenue(event);

Revenue Interface

NameTypeDescriptionDefault
productId (optional)stringAn identifier for the product. We recommend something like the Google Play Store product ID.null
quantity (required)intThe quantity of products purchased. Note: revenue = quantity * price1
price (required)DoubleThe price of the products purchased, and this can be negative. Note: revenue = quantity * pricenull
revenueType (optional, required for revenue verification)StringThe type of revenue (e.g. tax, refund, income).null
eventProperties (optional)JSONObjectAn object of event properties to include in the revenue event.null

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.

import { setUserId } from '@amplitude/analytics-browser';

setUserId('[email protected]');

You can also assign the User ID as an argument to the init call.

import { init } from '@amplitude/analytics-browser';

init(API_KEY, '[email protected]');

Custom Session ID

You can assign a new Session ID using setSessionId(). When setting a custom session ID, make sure the value is in milliseconds since epoch (Unix Timestamp).

import { setSessionId } from '@amplitude/analytics-browser';

setSessionId(Date.now());

Custom Device ID

If your app has its own login system that you want to track users with, you can call setUserId at any time.

You can assign a new device ID using deviceId. When setting a custom device ID, make sure the value is sufficiently unique. A uuid is recommended.

import { setDeviceId } from '@amplitude/analytics-browser';
const { uuid } = require('uuidv4');

setDeviceId(uuid());

Tracking Switch

You can turn off logging for a given user by calling setOptOut.

import { setOptOut } from '@amplitude/analytics-browser';

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.

import { setOptOut } from '@amplitude/analytics-browser';

setOptOut(false);

Optional Tracking

By default, the 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.

Tracking Options

Default

city

true

country

true

carrier

true

deviceManufacturer

true

deviceModel

true

dma

true

ipAddress

true

language

true

osName

true

osVersion

true

platform

true

region

true

versionName

true

🚧

Important Note

The optional tracking configurations will only prevent default properties from being tracked on newly created projects, where data has not yet been sent. If you have a project with existing data that you would like to stop collecting the default properties for, please get help in the Amplitude Community. Note that the existing data will not be deleted.

Callback

All asynchronous API are optionally awaitable through a Promise interface. This also serves as callback interface.

import { track } from '@amplitude/analytics-browser';

// Using async/await
const results = await 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)

// Using promises
track('Button Clicked').promise.then((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)
});

Plugins

Plugins allow you to extend Amplitude SDK's behavior by, for example, modifying event properties (enrichment type) or sending to a third-party APIs (destination type). A plugin is an object with methods setup() and execute().

Plugin.setup

This method contains logic for preparing the plugin for use and has config as a parameter. The expected return value is undefined. A typical use for this method, is to copy configuration from config or instantiate plugin dependencies. This method is called when the plugin is registered to the client via client.add().

Plugin.execute

This method contains the logic for processing events and has event as parameter. If used as enrichment type plugin, the expected return value is the modified/enriched event; while if used as a destination type plugin, the expected return value is undefined. This method is called for each event, including Identify, GroupIdentify and Revenue events, that is instrumented using the client interface.

Plugin Examples

Enrichment Type Plugin

Here's an example of a plugin that modifies each event that is instrumented by adding an increment integer to event_id property of an event starting from 100.

import { BrowserConfig, EnrichmentPlugin, Event, PluginType } from '@amplitude/analytics-types';

export class AddEventIdPlugin implements EnrichmentPlugin {
  name = 'add-event-id';
  type = PluginType.ENRICHMENT as const;
  currentId = 100;
  
  /**
   * setup() is called on plugin installation
   * example: client.add(new AddEventIdPlugin());
   */
  setup(config: BrowserConfig): Promise<undefined> {
     this.config = config;
  }
   
  /**
   * execute() is called on each event instrumented
   * example: client.track('New Event');
   */
  execute(event: Event): Promise<Event> {
    event.event_id = this.currentId++;
    return event;
  }
}

Did this page help you?