Skip to content

Browser SDK

npm version

The Browser SDK lets you send events to Amplitude. This library is open-source, check it out on GitHub.

Browser SDK Resources

GitHub · Releases · API Reference

Browser SDK versus the Marketing Analytics Browser

Amplitude recommends the Browser SDK for most users. You can extend its functionality using plugins. However, if you want web attribution and page view tracking without extra setup, use the Marketing Analytics Browser SDK instead. It extends the Browser SDK with built-in web attribution and page view tracking. Learn more about Marketing Analytics Browser SDK.

Ampli Wrapper versus the Amplitude SDK

The Ampli Wrapper is an autogenerated library based on your pre-defined tracking plan. This is a lightweight wrapper over the Amplitude SDK that provides type-safety, automatic code completion, linting, and schema validation. The generated code replicates the spec in the Tracking Plan and enforces its rules and requirements. This guide is about the Amplitude SDK. To learn more about Ampli Wrapper, see Ampli Wrapper Overview and examples. Click here for more documentation on Ampli for Browser.

Getting started

Use this quickstart guide to get started with Amplitude Browser SDK.

Usage

Initialize the SDK

Important notes about sending events

This SDK uses the HTTP V2 API and follows the same constraints for events. Make sure that all events logged in the SDK have the event_type field and at least one of device_id or user_id, and follows 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 user_id or device_id value, the upload may be rejected with a 400 status. Override the default minimum length of 5 character by passing the min_id_length option with the request.

You must initialize the SDK before you can instrument any events. Your Amplitude project's API key is required. You can pass an optional user ID and config object in this call. You can use the SDK anywhere after it's initialized anywhere in an application.

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

// Option 2, initialize including user ID if it's already known
amplitude.init(API_KEY, 'user@amplitude.com');

// Option 3, initialize including configuration
amplitude.init(API_KEY, 'user@amplitude.com', configurationObj);

Configuration

Configuration Options
Name
Description Default Value
apiKey Required. string. The apiKey of your project. null
flushIntervalMillis number. The amount of time waiting to upload the event to the server in millionseconds. 1 second.
flushQueueSize number. The maximum number of events that can be stored locally before forcing an upload. 30 events.
flushMaxRetries number. The max retry limits. 5 times.
logLevel LogLevel.None or LogLevel.Error or LogLevel.Warn or LogLevel.Verbose or LogLevel.Debug. The log level. LogLevel.Warn
loggerProvider Logger. Implements a custom loggerProvider class from the Logger, and pass it in the configuration during the initialization to help with collecting any error messages from the SDK in a production environment. Amplitude Logger
minIdLength number. Overrides the minimum length of user_id & device_id fields. 5
optOut boolean. If optOut is true, the event isn't sent to Amplitude's servers. false
serverUrl string. The server url events upload to. https://api2.amplitude.com/2/httpapi
serverZone EU or US. Set Amplitude Server Zone, switch to zone related configuration. To send data to Amplitude's EU servers should configure to EU US
storageProvider Storage<Event[]>. Implements a custom storageProvider class from Storage. MemoryStorage
useBatch boolean. When true, uses the Batch API instead of the HTTP V2 API. false
transportProvider Transport. Custom HTTP client. For example, sending requests to your proxy server with customized HTTP request headers. Transport
transport TransportType.XHR or TransportType.SendBeacon or TransportType.Fetch. Set the transport type. TransportType.Fetch
appVersion string. The current version of your application. For example: "1.0.0" null
deviceId string. A device-specific identifier. UUID()
cookieExpiration number. The days when the cookie expires. 365 days.
cookieSameSite string. The SameSite attribute of the Set-Cookie HTTP response header. LAX
cookieSecure boolean. If restrict access to cookies or not. A cookie with the Secure attribute is only sent to the server with an encrypted request over the HTTPS protocol. false
cookieStorage Storage<UserSession>. Implements a custom cookieStorage class from Storage. MemoryStorage<UserSession>
disableCookies boolean. If disable cookies or not. If cookies is disable, using LocalStorage or MemoryStorage. The cookies is enable by default.
domain string. Set the top level domain. null
partnerId string. The partner Id value. Amplitude requires the customer who built an event ingestion integration to add the partner identifier to partner_id. null
sessionManager SessionManager. Implements a custom sessionManager class from SessionManager. SessionManager(new MemoryStorage<UserSession>(), '')
sessionTimeout number. How long one session expire. 30 minutes.
userId number. ID for the user. Must have a minimum length of 5 characters unless overridden with the min_user_length option. undefined
config.trackingOptions TrackingOptions. Please check the Optional tracking section for more tracking options configuration. Enable all tracking options by default.

In addition to the basic configuration options, there also has options to configure attribution.

Attribution Options
Name
Description Default Value
attribution.disabled boolean. Whether disable the attribution tracking. false
attribution.excludeReferrers string[]. Exclude the attribution tracking for the provided referrers string Including all referrers by default.
attribution.initialEmptyValue string. Customize the initial empty value for attribution related user properties to any string value. EMPTY
attribution.trackNewCampaigns boolean. Whether tracking new campaigns on the current session. false
attribution.trackPageViews boolean. Whether track page view on attribution. false

Configure batching behavior

To support high performance environments, the SDK sends events in batches. Every event logged by track method is queued in memory. Events are flushed in batch in background. You can customize batch behavior with flushQueueSize and flushIntervalMillis. By default, the serverUrl will be https://api2.amplitude.com/2/httpapi. For customers who want to send large batches of data at a time, set useBatch to true to set setServerUrl to batch event upload api https://api2.amplitude.com/batch. Both the regular mode and the batch mode use the same events upload threshold and flush time intervals.

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  // Events queued in memory will flush when number of events exceed upload threshold
  // Default value is 30
  flushQueueSize: 50, 
  // Events queue will flush every certain milliseconds based on setting
  // Default value is 10000 milliseconds
  flushIntervalMillis: 20000,
  // Using batch mode with batch API endpoint, `https://api2.amplitude.com/batch`
  useBatch: true
});

EU data residency

You can configure the server zone when initializing the client for sending data to Amplitude's EU servers. The SDK sends data based on the server zone if it's set.

Note

For EU data residency, the project must be set up inside Amplitude EU. You must initialize the SDK with the API key from Amplitude EU.

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  serverZone: 'EU',
});

Debugging

You can control the level of logs printed to the developer console.

  • 'None': Suppresses all log messages.
  • 'Error': Shows error messages only.
  • 'Warn': Shows error messages and warnings. This is the default value if logLevel isn't explicitly specified.
  • 'Verbose': Shows informative messages.
  • 'Debug': Shows error messages, warnings, and informative messages that may be useful for debugging, including the function context information for all SDK public method invocations. This logging mode is only suggested to be used in development phases.

Set the log level by configuring the logLevel with the level you want.

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  logLevel: amplitude.Types.LogLevel.Warn,
});

The default logger outputs logs 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(API_KEY, OPTIONAL_USER_ID, {
  loggerProvider: new MyLogger(),
});
Debug Mode

Enable the debug mode by setting the logLevel to "Debug", example:

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  logLevel: amplitude.Types.LogLevel.Debug,
});

With the default logger, extra function context information will be output to the developer console when invoking any SDK public method, including:

  • 'type': Category of this context, e.g., "invoke public method".
  • 'name': Name of invoked function, e.g., "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.

Tracking an event

Important notes about sending events

This SDK uses the HTTP V2 API and follows the same constraints for events. Make sure that all events logged in the SDK have the event_type field and at least one of device_id or user_id, and follows 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 user_id or device_id value, the upload may be rejected with a 400 status. Override the default minimum length of 5 character by passing the min_id_length option with the request.

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

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

// Track events with optional properties
const eventProperties = {
  buttonColor: 'primary',
};
amplitude.track('Button Clicked', eventProperties);

Tracking default events

Starting version 1.9.1, Browser SDK now tracks default events. Browser SDK can be configured to track the following events automatically:

  • Page views
  • Sessions
  • Form interactions
  • File downloads
Tracking default events options
Name
Value Description
config.defaultTracking.pageViews Optional. boolean Enables default page view tracking. If value is true, Amplitude tracks page view events on initialization. Default value is false.

Event properties tracked includes: [Amplitude] Page Domain, [Amplitude] Page Location, [Amplitude] Page Path, [Amplitude] Page Title, [Amplitude] Page URL

See Tracking page views for more information.
config.defaultTracking.sessions Optional. boolean Enables session tracking. If value is true, Amplitude tracks session start and session end events. Default value is false.

See Tracking sessions for more information.
config.defaultTracking.formInteractions Optional. boolean Enables form interaction tracking. If value is true, Amplitude tracks form start and form submit events. Default value is false.

Event properties tracked includes: [Amplitude] Form ID, [Amplitude] Form Name, [Amplitude] Form Destination

See Tracking form interactions for more information.
config.defaultTracking.fileDownloads Optional. boolean Enables file download tracking. If value is true, Amplitude tracks file download events. Default value is false.

Event properties tracked includes: [Amplitude] File Extension, [Amplitude] File Name, [Amplitude] Link ID, [Amplitude] Link Text, [Amplitude] Link URL

See Tracking file downloads for more information.

You can enable Amplitude to start tracking all events mentioned above, use the code sample below. Otherwise, you can omit the configuration to keep them disabled.

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  defaultTracking: {
    pageViews: true,
    sessions: true,
    formInteractions: true,
    fileDownloads: true,
  },
});

Alternatively, you can enable Amplitude to track all events mentioned above by setting config.defaultTracking to true.

Note

Amplitude may add more events in a future version, and this configuration enables tracking for those events as well.

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  defaultTracking: true,
});

Tracking page views

You can enable Amplitude to start tracking page view events by setting config.defaultTracking.pageViews to true. Refer to the code sample below.

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  defaultTracking: {
    pageViews: true,
  },
});

By setting config.defaultTracking.pageViews to true, you enable Amplitude to use default page view tracking behavior. The default behavior sends a page view event on initialization. The event type for this event is "[Amplitude] Page Viewed".

Advanced configuration for tracking page views

You can also use advanced configuration for better control of when page views event are sent.

Tracking page views options
Name
Value Description
defaultTracking.pageViews.trackOn Optional. "attribution" or () => boolean Provides advanced control on when page view events are tracked.

You can omit or set the value to undefined, and configure page view events to be tracked on initialization.

You can set the value to "attribution" and configure page view events to be tracked only when web attribution are tracked.

You can set the value to a function that returns a boolean (true or false) and configure page view events to be tracked based on your criteria.
defaultTracking.pageViews.trackHistoryChanges Optional. "pathOnly" or "all" Provides advanced control for single page application on when page views are tracked.

You can omit or set the value to "all", and configure page view events to be tracked 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.

You can omit or set the value to "pathOnly", and configure page view events to be tracked 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.

For example, you can configure Amplitude to track page views only when the URL path contains a certain substring, let’s say “home”. Refer to the code sample for how to achieve this.

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  defaultTracking: {
    pageViews: {
      trackOn: () => {
        return window.location.pathname.includes('home');
      },
    },
  },
});

Tracking sessions

You can enable Amplitude to start tracking session events by setting config.defaultTracking.sessions to true. Refer to the code sample below.

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  defaultTracking: {
    sessions: true,
  },
});

By setting config.defaultTracking.sessions to true, you enable Amplitude to track session start and session end events. 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 is and is the first event of the session. The event type for session start is "[Amplitude] Start Session". When an existing session ends, a session start end is tracked and is the last event of the session. The event type for session end is "[Amplitude] End Session".

Tracking form interactions

You can enable Amplitude to start tracking form interaction events by setting config.defaultTracking.formInteractions to true. Refer to the code sample below.

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  defaultTracking: {
    formInteractions: true,
  },
});

By setting config.defaultTracking.formInteractions to true, you enable Amplitude to track form start and form submit events. A form start event is tracked when the user initially interacts with the form. An initial interaction can be the first change to an text input, or radio button, or dropdown. The event type for session start is "[Amplitude] Form Started". A form submit event is tracked when the user submits the form. The event type for session start is "[Amplitude] Form Submitted". If a form is submitted with no initial change to any form fields, both "[Amplitude] Form Started" and "[Amplitude] Form Submitted" are tracked.

Amplitude can track forms that are 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>

Tracking file downloads

You can enable Amplitude to start tracking file download events by setting config.defaultTracking.fileDownloads to true. Refer to the code sample below.

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  defaultTracking: {
    fileDownloads: true,
  },
});

By setting config.defaultTracking.fileDownloads to true, you enable Amplitude to track file download events. A file download event is tracked when an anchor or <a> tag linked to a file is clicked. The event type for file download is "[Amplitude] File Downloaded". 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

User properties

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

Note

If the Identify call is sent after the event, the results of operations are visible immediately in the dashboard user’s profile area. However, they don't appear in chart results until another event is sent after the Identify call. The identify call only affects events going forward. More details here.

Set a user property

The Identify object provides controls over setting user properties. It works like this: first, instantiate an Identify object, then call Identify methods on it, and finally, the client can make a call with the Identify object.

const identifyEvent = new amplitude.Identify();
amplitude.identify(identifyEvent);

Identify.set

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', 'LAX');

amplitude.identify(identifyEvent);

Identify.setOnce

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 and because only the initial value is tracked, setOnce() ignores later calls.

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

identify(identifyEvent);

Identify.add

This method increments a user property by some 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);

Arrays in user properties

You can use arrays as user properties. 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 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);

Identify.append

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);

Identify.preInsert

This method pre-inserts a value or values to a user property, if it doesn't exist in the user property yet. Pre-insert means inserting the values at the beginning 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 pre-inserted. If the user property has an existing value, this method is a no-op.

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

identify(identifyEvent);

Identify.postInsert

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);

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 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);

User groups

Feature availability

This feature is available in accounts with a Growth or Enterprise plan with the Accounts add-on.

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 indicate that a user is in multiple groups.

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

// set group with multiple group names
amplitude.setGroup('sport', ['soccer', 'tennis']);

Group properties

Feature availability

This feature is available in accounts with a Growth or Enterprise plan with the Accounts add-on.

Use the Group Identify API to set or update 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);

Revenue tracking

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 (such as '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, 3 units of a product was purchased at $3.99.

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

amplitude.revenue(event);

Revenue interface

Name Description
product_id Optional. String. An identifier for the product. Amplitude recommend something like the Google Play Store product ID. Defaults to null.
quantity Required. Int. The quantity of products purchased. Note: revenue = quantity * price. Defaults to 1
price Required. Double. The price of the products purchased, and this can be negative. Note: revenue = quantity * price. Defaults to null.
revenue_type Optional, but required for revenue verification. String. The revenue type (for example, tax, refund, income). Defaults to null.
receipt Optional. String. The receipt identifier of the revenue. Defaults to null
receipt_sig Optional, but required for revenue verification. String. The receipt signature of the revenue. Defaults to null.
properties Optional. JSONObject. An object of event properties to include in the revenue event. Defaults to null.

Flush the event buffer

The flush method triggers the client to send buffered events immediately.

amplitude.flush();

By default, flush is called automatically in an interval, if you want to flush the events all together, you can control the async flow with the optional Promise interface, example:

amplitude.init(API_KEY).promise.then(function() {
  amplitude.track('Button Clicked');
  amplitude.flush();
});

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.setUserId('user@amplitude.com');

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

amplitude.init(API_KEY, 'user@amplitude.com');

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

amplitude.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. Amplitude recommends using a UUID.

amplitude.setDeviceId(uuid());

Reset when user logs out

reset is a shortcut to anonymize users after they log out, by:

  • setting userId to undefined
  • setting deviceId to a new UUID value

With an undefined userId and a completely new deviceId, the current user would appear as a brand new user in dashboard.

amplitude.reset();

Opt users out of tracking

You can turn off logging for a given user by setting setOptOut to true.

amplitude.setOptOut(true);

Events aren't saved or sent to the server while setOptOut is enabled, and the setting persists across page loads.

Re-enable logging by setting setOptOut to false.

amplitude.setOptOut(false);

Optional tracking

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
deviceManufacturer true
deviceModel true
ipAddress true
language true
osName true
osVersion true
platform true
amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  trackingOptions: {
    deviceManufacturer: false,
    deviceModel: false,
    ipAddress: false,
    language: false,
    osName: false,
    osVersion: false,
    platform: false,
  },
});

Callback

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

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)
});
import * as amplitude from '@amplitude/analytics-browser';

// Using async/await
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

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

add

The add method adds a plugin to Amplitude. Plugins can help processing and sending events.

amplitude.add(new Plugin());

remove

The remove method removes the given plugin name from the client instance if it exists.

amplitude.remove(plugin.name);

Create your custom plugin

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 amplitude.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. If used as a destination type plugin, the expected return value is a map with keys: event (BaseEvent), code (number), and message (string). This method is called for each event that's instrumented using the client interface, including Identify, GroupIdentify and Revenue events.

Plugin examples

Destination type plugin

Here's an example of a plugin that sends each event that's instrumented to a target server URL using your preferred HTTP client.

function myDestinationPlugin (serverUrl) {
  const name = 'my-destination-plugin';
  const type = amplitude.Types.PluginType.DESTINATION;
  let amplitudeConfig;

  /**
   * setup() is called on plugin installation
   * example: amplitude.add(new myDestinationPlugin());
   */
  const setup = function (config) {
    amplitudeConfig = config;
  }

  /**
   * execute() is called on each event instrumented
   * example: amplitude.track('New Event');
   */
  const execute = function (event) {
    const payload = {
      key: 'secret',
      data: event,
    };
    return fetch(this.serverUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: '*/*',
      },
      body: JSON.stringify(payload),
    }).then(function(response) {
      return {
        code: response.status,
        event: event,
        message: response.statusText,
      };
    });
  }

  return {
    name,
    type,
    setup,
    execute,
  },
}

amplitude.init(API_KEY);
amplitude.add(myDestinationPlugin('https://custom.domain.com'));
Enrichment type plugin

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

const addEventIdPlugin = () => {
  const name = 'add-event-id';
  const type = amplitude.Types.PluginType.ENRICHMENT;
  let currentId = 100;
  let amplitudeConfig;

  /**
   * setup() is called on plugin installation
   * example: amplitude.add(new AddEventIdPlugin());
   */
  const setup = function (config) {
    amplitudeConfig = config;
  }

  /**
   * execute() is called on each event instrumented
   * example: client.track('New Event');
   */
  const execute = function (event: Event) {
    event.event_id = currentId++;
    return event;
  }

  return {
    name,
    type,
    setup,
    execute,
  }
}

amplitude.init(API_KEY);
amplitude.add(addEventIdPlugin());
Web attribution enrichment plugin

You need to download plugin-web-attribution-browser package and add the webAttributionPlugin before call init method.

npm install @amplitude/plugin-web-attribution-browser
yarn add @amplitude/plugin-web-attribution-browser

Add plugin to Amplitude instance.

amplitude.add(webAttributionPlugin());
amplitude.init(API_KEY);

See the configuration options. Learn more about what the Web Attribution Plugin supports.

Differences from base SDK

Enabling the Attribution plugin overwrites the default attribution tracking behavior of the SDK.

The SDK’s built in attribution tracking only tracks attribution at the start of sessions. This mean if a user re-enters the site through a new campaign channel (such as direct or an ad) in the middle of a session, this new channel isn't recorded.

If the trackNewCampaigns option is set to true, the campaigns are tracked, and the user’s session is reset when a new campaign is detected.

The Attribution plugin tracks all campaigns, regardless of whether the user is at the start of a session.

Set the resetSessionOnNewCampaign option to true to cause the user’s session to be reset when a new campaign is detected. The session isn't reset in the case where the referrer is just a different subdomain of your site.

Page view enrichment plugin

You need to download plugin-page-view-tracking-browser and add the pageViewTrackingPlugin before calling the init method.

npm install @amplitude/plugin-page-view-tracking-browser
yarn add @amplitude/plugin-page-view-tracking-browser

Add plugin to Amplitude instance.

amplitude.add(pageViewTrackingPlugin());
amplitude.init(API_KEY);

See the configuration options. Learn more about what the Page View Plugin supports.

Differences from base SDK

The base SDK sends Page View events when a user’s campaign is tracked if the attribution.trackPageViews option is set to true.

The page view plugin sends a Page View event on each page a user visits by default. It also offers options to customize this behavior.

Advanced topics

Cross domain tracking

You can track anonymous behavior across two different domains. Amplitude identifies anonymous users by their device IDs which must be passed between the domains. For example:

  • Site 1: www.example.com
  • Site 2: www.example.org

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

  1. From Site 1, grab the device ID from getDeviceId().
  2. Pass the device ID to Site 2 via a URL parameter when the user navigates. (for example: www.example.com?deviceId=device_id_from_site_1)
  3. Initialize the Amplitude SDK on Site 2 with init('API_KEY', null).

If the deviceId isn't provided with the init like init('API_KEY', null, { deviceId: 'custom-device-id' }), then it automatically fallbacks to use URL parameter.

Custom HTTP client

You can provide an implementation of Transport interface to the transportProvider configuration option for customization purpose, for example, sending requests to your proxy server with customized HTTP request headers.

class MyTransport {
  send(serverUrl, payload) {
    // check example: https://github.com/amplitude/Amplitude-TypeScript/blob/main/packages/analytics-client-common/src/transports/fetch.ts
  }
}

amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  transportProvider: new MyTransport(),
});

Content Security Policy (CSP)

If your web app configures the strict Content Security Policy (CSP) for security concerns, adjust the policy to whitelist the Amplitude domains:

  • When using "Script Loader", add https://*.amplitude.com to script-src.
  • Add https://*.amplitude.com to connect-src.

Still have questions? Ask them in the Community.