Install and configure the SDK

Install the Amperity Event Streams SDK on your website, configure it with the write key and collector URL from your event stream, and then send events.

Prerequisites

  1. Create an event stream that uses the Amperity Event Streams SDK.

  2. Copy the Endpoint and a Write key from the event stream settings page.

Install the SDK

You can add the SDK to your website in one of two ways. Use the npm package if your site is built with a bundler, such as Vite, webpack, or Next.js. Use the script tag if you want to paste a snippet into your pages without a build step. Both ways send the same events, and both need the write key and the Endpoint from the event stream settings page.

Install with npm

Add the @amperity/event-streams-browser package to your project:

npm install @amperity/event-streams-browser

The package has no runtime dependencies. It provides ES modules, CommonJS, and type declarations, so it works with the bundlers and frameworks that most sites use.

Load the SDK and send events

Import the SDK where your application starts, load it with the write key and Endpoint from the event stream settings page, and then send events:

import { amperity } from '@amperity/event-streams-browser';

await amperity.load({
  writeKey: '{write-key}',
  endpoint: '{collector-url}'
});

// Record a page view. In a single-page app, call this on each route change.
amperity.page();

// When a visitor signs in or is otherwise identified, call identify()
// with their user ID and any identifiers, such as an email address.
amperity.identify('cust-771', { email: 'ana@example.com' });

// Record an action the visitor takes, such as a purchase, with its details.
amperity.track('Order Completed', {
  order_id: 'A-1001',
  total: 271.4,
  currency: 'USD'
});

Replace {write-key} with a write key from the event stream settings page. Replace {collector-url} with the Endpoint from the same page. Pass the host only. The SDK builds the full collector address from the endpoint and the write key, so you don’t add a path.

amperity.load() is the only call that is required before you send events. Pass more options to it to change how the SDK stores identifiers, ends sessions, and handles consent. See Load options.

The SDK runs only in a browser. If your application renders pages on a server, such as a Next.js app, call amperity.load() from code that runs in the browser, for example inside an effect that runs after the page mounts. Importing the package on the server is safe, but a load() call there is rejected. In a single-page app, call amperity.page() each time the route changes.

Install with a script tag

Paste the following snippet into the <head> element of every page where you want to collect events:

<script>
  (function (w, d) {
    var a = w.amperity = w.amperity || function (key) {
      var instance = {};
      a.instanceMethods.forEach(function (m) { instance[m] = function () { a.q.push([key, m].concat(Array.prototype.slice.call(arguments))); }; });
      return instance;
    };
    if (a.invoked) { console.error('Amperity snippet included twice.'); return; }
    a.invoked = true; a.q = [];
    a.instanceMethods = ['track', 'page', 'identify', 'reset', 'getUserId', 'getUserTraits', 'on', 'once', 'off'];
    a.instanceMethods.concat(['load', 'ready', 'all', 'consent', 'setAnonymousId', 'getAnonymousId']).forEach(function (m) {
      a[m] = function () { a.q.push([m].concat(Array.prototype.slice.call(arguments))); };
    });
    var s = d.createElement('script'); s.async = true;
    s.src = 'https://cdn.amperity.com/event-streams-browser/v1/amperity.js';
    d.head.appendChild(s);
  })(window, document);
  amperity.load({ writeKey: '{write-key}', endpoint: '{collector-url}' });
  amperity.page();
</script>

Replace {write-key} with a write key from the event stream settings page. Replace {collector-url} with the Endpoint from the same page.

The snippet loads the SDK without blocking your page. Calls that your page makes before the SDK finishes loading are queued and run in order once it is ready. The last two lines are yours: the first loads the SDK with your settings, and the second records a page view. If your site is a single-page app that records page views itself on each route change, remove the amperity.page() line.

The v1 address always serves the latest 1.x release. To pin your site to one release, replace v1 in the address with the full version, such as v1.0.0.

Load options

Pass options to amperity.load() to configure the SDK. The script tag snippet and the npm package take the same options. Only writeKey and endpoint are required.

Option

Description

writeKey

Required. The write key for the event stream.

endpoint

Required. The Endpoint from the event stream settings page. Pass the host only, with or without https://. The SDK always uses https and adds the path and the write key.

storage

Configures the cookie that stores the anonymous ID: cookieDomain, sameSite, secure, and expiryDays. By default the SDK uses the registrable domain of your site, Lax, false, and 365 days.

identity

Configures what identify() and reset() do. Set deepMergeTraits to true to merge nested traits instead of only the top level, and resetAnonymousId to true to create a new anonymous ID when reset() is called. Both default to false.

anonymousIdMigration

A list of cookie or localStorage names from another tool, such as ajs_anonymous_id. If the SDK has no anonymous ID yet, it adopts the first value it finds, so a visitor keeps one ID when you switch tools.

sessions

Sets timeout, the time in milliseconds without an event after which a session ends. The default is 30 minutes, and the minimum is 10 seconds.

consent

Configures consent behavior: provider, which accepts only custom, and bufferPreDecisionEvents. See Consent.

logLevel

Sets how much the SDK writes to the browser console: error, warn, info, debug, or none. The default is error.

Note

If you call amperity.load() more than once, the SDK keeps the first configuration and ignores later calls.

Supported browsers

The SDK supports Chrome and Edge 91, Firefox 74, Safari 14.1 on macOS, and Safari 14.5 on iOS, and later versions of each. The SDK runs only in a browser. Outside a browser, importing the package works, but amperity.load() rejects with an UnsupportedEnvironmentError.

Send events

After the SDK is loaded, call these methods to send events:

Method

Description

amperity.page(category, name, properties)

Sends a page event that is named page_view. Call it on each page load, or on each route change in a single-page app. All three arguments are optional. One string is the page name, and two strings are the category and the name. The SDK fills in the page’s path, URL, referrer, query string, and title when you don’t pass them.

amperity.track(name, properties)

Sends a track event with the name you pass, such as Product Viewed or Order Completed, and optional properties.

amperity.identify(userId, traits)

Stores the user ID and traits, and then sends an identify event that is named identity_set. Every later event carries the user ID and traits. You can pass a user ID, traits such as email, or both.

amperity.reset()

Clears the stored user ID and traits and starts a new session. Call it when a customer signs out. It does not send an event, and the anonymous ID stays the same unless you set identity.resetAnonymousId.

amperity.consent(granted, details)

Records a visitor’s consent decision. See Consent.

amperity.getAnonymousId(), amperity.getUserId(), amperity.getUserTraits()

Return the stored anonymous ID, user ID, and traits. They never change the stored values.

amperity.setAnonymousId(id)

Stores a visitor ID that your site created. Call it without an ID, or with an empty string, to create a new one.

amperity.track('Order Completed', {
  order_id: '1001',
  total: 42.00,
  currency: 'USD'
});

An event stream recognizes SDK events by the name that the SDK sends in the event field. Page events are named page_view, identify events are named identity_set, and track events use the name you pass.

page(), track(), and identify() return a promise. The promise resolves when the SDK has queued the event for delivery, not when Amperity has received it. The result has the event as the SDK sends it, and a lastFailure() method. lastFailure() returns undefined until a delivery attempt fails or the SDK drops the event. Then it returns an object with a reason and a message. The reason is one of the following:

  • http: Amperity answered with a status that was not successful. The object also has the statusCode.

  • network: the request did not reach Amperity.

  • consent: the SDK did not send the event because consent was not granted.

  • overflow: the SDK dropped the event because too many events were waiting to be sent.

page(), track(), and identify() reject with a ValidationError when an argument cannot be sent, such as properties that contain a circular reference. The error names the argument in its field. A call made before amperity.load() rejects with a NotLoadedError.

Delivery and retries

The SDK sends each event in its own request as soon as the event is created. It has at most 10 requests in flight at a time, and it sends the next waiting event when a request ends.

  • Retries. The SDK sends an event again when Amperity answers 429 or a 5xx status, or when the request does not reach Amperity. It waits 1 second after the first failure and about 1.5 times longer after each later failure, up to 9 minutes, with some random variation. It makes up to 35 attempts. A request that is not answered in 30 seconds counts as a network failure. The SDK does not send an event again when Amperity answers any other 4xx status.

  • Page close. When a visitor leaves a page, the SDK saves each event that was not delivered and sends it once more in a way that survives the page closing. The next page on your site that loads the SDK with the same write key sends the events that are still saved.

  • Memory limit. When more than 1 MB of events are waiting, the SDK drops the oldest events. lastFailure() reports these events with the reason overflow.

  • Event size. When an event is larger than 32 KiB as JSON, the SDK still sends it, and it writes a warning to the console when logLevel is warn, info, or debug. Amperity rejects an event larger than 64 KiB.

Data the SDK collects

The SDK adds the following context to every event:

  • Page: path, URL, referrer, query string, and title.

  • Campaign: the UTM parameters in the page URL, such as utm_source, utm_medium, and utm_campaign. The SDK removes the utm_ prefix and names utm_campaign as name.

  • Browser and device: locale, user agent, time zone, screen size and density, and basic client hints in Chromium browsers.

  • Identity and session: the anonymous ID and a session ID. After you call identify(), the user ID and traits.

  • Consent: the consent decision, after one is made.

  • SDK: the SDK name and version, and a channel value of web.

Every event also has a unique eventId, the visitor’s anonymousId, and the time the event occurred.

Identity

The SDK generates an anonymous ID for each visitor and stores it in the amperity_anonymous_id cookie. If cookies are not available, the SDK falls back to localStorage, then sessionStorage, and then memory. By default the cookie expires after 365 days. Some browsers, such as Safari, limit how long a script can keep a cookie. To use an ID that your site created, call amperity.setAnonymousId(). To keep the ID that another tool created, list the tool’s cookie or localStorage name in the anonymousIdMigration option.

When you call amperity.identify(), the SDK stores the user ID and traits in localStorage and adds them to every later event. If you identify the same user ID again, the new traits are merged into the stored traits. Only the top-level traits are merged, unless you set identity.deepMergeTraits to true. A different user ID replaces the stored traits. Use amperity.reset() to clear them.

Amperity resolves the identifiers in events to customer profiles. For example, if you call identify() with an email trait, Amperity can use the email address to recognize the customer.

A session ends after 30 minutes without an event. Change this time with the sessions.timeout option.