On this page

Marketing Analytics SDK

The Marketing Analytics Browser SDK extends the Browser SDK to identify users and events based on marketing channels. This library is open-source. View the source on GitHub.

This is a maintenance SDK and only receives bug fixes until deprecation. An improved version of Amplitude Browser SDK is now available. Amplitude Browser SDK 2.0 features default event tracking, improved marketing attribution tracking, a simplified interface, and a lighter weight package. Amplitude recommends the Browser SDK 2.0 for both product analytics and marketing analytics use cases. Upgrade to the latest Browser SDK 2.0.

Install the SDK

To get started with the Marketing Analytics Browser SDK, install the package in your project with npm or the script loader.

Install the Node package

bash
npm install @amplitude/marketing-analytics-browser

Install with the script loader

Amplitude also distributes this package through a CDN. Copy and paste this script in your HTML file.

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

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

Configuration

The Marketing Analytics SDK supports the following options to configure web attribution and page view tracking.

Configure batching behavior

To support high-performance environments, the SDK sends events in batches. The SDK queues every event logged by the track method in memory. The SDK flushes events in batches in the background. Customize batch behavior with flushQueueSize and flushIntervalMillis. By default, the serverUrl is https://api2.amplitude.com/2/httpapi. To send large batches of data at a time, set useBatch to true to set setServerUrl to the batch event upload API at https://api2.amplitude.com/batch. Both the regular mode and the batch mode use the same events upload threshold and flush time intervals.

ts
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

Configure the server zone when you initialize the client to send data to Amplitude's EU servers. The SDK sends data based on the server zone if you set it.

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.

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

Marketing attribution

Amplitude tracks marketing attribution to identify your user's traffic source using the UTM, referrer, and click ID parameters.

UTM parameters

UTM (Urchin Traffic Monitor) parameters help you analyze the effectiveness of different ad campaigns and referring sites. UTM parameters are case-sensitive, so Amplitude treats them as different values when the capitalization varies.

There are five different standard UTM parameters:

Here is an example URL with UTM parameters:

https://www.amplitude.com/?utm_source=newsletter&utm_campaign=product_analytics_playbook&utm_medium=email&utm_term=product%20analytics&utm_content=banner-link

Referrer parameters

Referrer is the URL of the page that linked to the destination page. Amplitude tracks the following parameters:

The referrer is an empty string ('') if the user navigated to the destination page directly.

Click ID parameters

Click IDs are campaign identifiers included as URL query parameters. Ad platforms use these IDs to identify the campaign and other attributes. Amplitude doesn't have access to further campaign attributes associated with click IDs, but Amplitude can track click ID values specified in the following table.

First-touch attribution

Amplitude captures the initial attribution data at the start of the first session. Amplitude sets the first-touch attribution values when it sees a user's attribution data for the first time. Amplitude sets the following user properties one time:

  • initial_utm_source.
  • initial_utm_medium.
  • initial_utm_campaign.
  • initial_utm_term.
  • initial_utm_content.
  • initial_referrer.
  • initial_referring_domain.
  • initial_gclid.
  • initial_fbclid.
  • initial_dclid.
  • initial_gbraid.
  • initial_ko_click_id.
  • initial_msclkid.
  • initial_ttclid.
  • initial_twclid.
  • initial_wbraid.
  • initial_li_fat_id.
  • initial_rdt_cid.

Multi-touch attribution

Amplitude captures the attribution data at the start of each session and sets those values as user properties. For organic or direct traffic, these properties may not be available. In that case, Amplitude unsets these user properties from the user identity.

For every new campaign (when Amplitude sees new attribution data), Amplitude captures the changes regardless of the state of the user session. Configure resetSessionOnNewCampaign to true to reset the session on every new campaign. The default behavior doesn't reset the session on a new campaign.

Amplitude tracks the following as user properties:

  • utm_source.
  • utm_medium.
  • utm_campaign.
  • utm_term.
  • utm_content.
  • referrer.
  • referring_domain.
  • gclid.
  • fbclid.
  • dclid.
  • gbraid.
  • ko_click_id.
  • msclkid.
  • ttclid.
  • twclid.
  • wbraid.
  • li_fat_id.
  • rdt_cid.

For users who initially visit a page directly or organically, the initial value defaults to "EMPTY". To use a different initial value, set attribution.initialEmptyValue to any string value.

ts
amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  attribution: {
    initialEmptyValue: "none",
  },
});

Exclude the referrers from a specific domain

Configure Amplitude to opt out of attribution data collection for a given list of referrers.

ts
amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  attribution: {
    excludeReferrers: ["www.test.com"],
  },
});

Reset the session on a new campaign

Configure Amplitude to start a new session if any campaign parameter changes by setting attribution.resetSessionOnNewCampaign to true. By default, attribution.resetSessionOnNewCampaign is false.

ts
amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  attribution: {
    resetSessionOnNewCampaign: true,
  },
});

Disable attribution tracking

Configure Amplitude to opt out of automatic attribution data collection by setting attribution.disabled to true. By default, attribution.disabled is false.

ts
amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  attribution: {
    disabled: true,
  },
});

Page view

Enable page view tracking by setting pageViewTracking to true. The SDK fires the page view event when the page loads.

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

Set pageViewTracking to an object to pass more options.

Track the page view event when the attribution changes

Set the trackOn option to 'attribution' to send Page View events only when attribution information changes.

ts
amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  pageViewTracking: {
    trackOn: "attribution",
  },
});

Track the page view event based on specific criteria

You can also set trackOn to a function callback to fully customize when the SDK sends a Page View event.

ts
amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  pageViewTracking: {
    trackOn: () => {
      return window.location.pathname === "/landing_page";
    },
  },
});

Single page app page view tracking

If you have a single page app that uses a history-based router such as react-router, enable trackHistoryChanges to send Page View events when users navigate between pages. Possible values for trackHistoryChanges:

Set trackHistoryChanges to pathOnly to track only path changes. By default, the SDK considers the full page URL when checking for page view changes.

ts
amplitude.init(API_KEY, OPTIONAL_USER_ID, {
  pageViewTracking: {
    trackHistoryChanges: "pathOnly", // or 'all'
  },
});

The SDK tracks the following information in page view events.

Use the Marketing Analytics SDK with Ampli

Use Ampli with this SDK by passing an instance of the Marketing Analytics SDK to ampli.load().

  1. Add the Marketing Analytics Browser SDK to your project.
  2. Create an instance of the SDK.
  3. Pass the instance into ampli.load().

This example passes the "amplitude" instance to ampli.load.

ts
amplitude.init(REACT_APP_AMPLITUDE_API_KEY, undefined, {
  ...DefaultConfiguration,
  logLevel: 3,
});
ampli.load({
  client: {
    instance: amplitude,
  },
});

Was this helpful?