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¶
Create an event stream that uses the Amperity Event Streams SDK.
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 |
|---|---|
|
Required. The write key for the event stream. |
|
Required. The Endpoint from the event stream settings page. Pass the host only, with or without |
|
Configures the cookie that stores the anonymous ID: |
|
Configures what |
|
A list of cookie or |
|
Sets |
|
Configures consent behavior: |
|
Sets how much the SDK writes to the browser console: |
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 |
|---|---|
|
Sends a |
|
Sends a |
|
Stores the user ID and traits, and then sends an |
|
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 |
|
Records a visitor’s consent decision. See Consent. |
|
Return the stored anonymous ID, user ID, and traits. They never change the stored values. |
|
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 thestatusCode.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
429or a5xxstatus, 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 other4xxstatus.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 reasonoverflow.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
logLeveliswarn,info, ordebug. 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, andutm_campaign. The SDK removes theutm_prefix and namesutm_campaignasname.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.
Consent¶
If you configure the consent option, the SDK waits for a consent decision before it sends events or stores identifiers. The SDK does not read a visitor’s consent from a consent banner or a consent management platform. Your site passes each decision to the SDK by calling amperity.consent(), for example from your banner’s or your consent management platform’s callback. Set the provider option to custom, which is its default and its only value.
With consent configured:
Until a decision is made, the SDK holds events in memory. Set
bufferPreDecisionEventstofalseto drop those events instead.When you call
amperity.consent(true), the SDK sends the held events and continues to send new events.When you call
amperity.consent(false), the SDK drops held events and does not send new events.
After a decision is made, each event includes the consent decision and any details you pass.
The SDK keeps the decision only for the current page. Call amperity.consent() with the visitor’s decision on every page, after amperity.load(). Events that the SDK holds without a decision are lost when the visitor leaves the page.
Important
If you do not configure the consent option, the SDK sends events without waiting for a decision. Review your privacy and legal requirements before you install the SDK.