Web

Tracking a website or web app with our browser SDK and a Project token: install, init, track, identify, autocapture, consent, and the dependency-free fallback.

Browser tracking uses our own browser SDK, @intelligent-page/analytics-web, with a Project token (ipa_pub_…). The token is write-only and safe to ship in a bundle: it is rejected on every route that returns data. If you would rather add no dependency at all, the same events can be posted with fetch and sendBeacon; that recipe is at the end of this page.

At a glance

Note

The package is built in this repository but the npm publish and the upload of the script-tag build to the ingest host are human release steps that have not run yet. Until they do, build it from packages/analytics-web (node build.mjs) and vendor dist/, or use the dependency-free recipe below. Both paths send identical events, so switching later changes no data.

Install

npm install @intelligent-page/analytics-web

Or a script tag, which starts itself:

<script src="https://t.intelligent.page/sdk/v1.js" data-token="ipa_pub_REPLACE_ME"></script>

The tag reads four attributes: data-token (required), data-host to send somewhere else, data-autocapture="0" to turn autocapture off, and data-page="0" to suppress the automatic first pageview. It exposes the same methods on window.ipAnalytics.

Init

import { createAnalytics } from '@intelligent-page/analytics-web';

export const analytics = createAnalytics({
  token: 'ipa_pub_REPLACE_ME',
  host: 'https://t.intelligent.page',
  autocapture: true,
});

Create it once for the page's lifetime and export it; a second instance per route loses the queue.

Track

analytics.page();                                     // a $pageview for the current URL
analytics.track('Signed Up', { plan: 'free' });
analytics.register({ appVersion: '4.2.0' });          // merged into every later event
analytics.unregister('appVersion');

track takes an event name of 1 to 96 characters (interior spaces are fine) and a flat properties object. register holds super properties in localStorage, so they survive a reload and attach to every event until you remove them.

Identify

analytics.identify('user_1024', { email: 'ada@example.com', plan: 'free' });
analytics.alias('ada@example.com');                   // a second id for the same person
analytics.group('shop', 'acme.myshopify.com', { name: 'Acme' });
analytics.people.set({ plan: 'pro' });                // a $set profile update
analytics.reset();                                    // sign-out: a new anonymous visitor

identify is safe to call on every page load: the SDK emits $identify once per anonymous-id and user-id pair and keeps the marker in localStorage, so a reload does not re-merge a history that is already merged. Traits produce a $set alongside it. alias takes the new id only; the person it attaches to is whoever the client is currently tracking. Read Identity and merge before you rely on the exact semantics, because what identify merges and what alias deliberately does not are different answers.

Verify in the Live view

curl -N https://t.intelligent.page/v1/live -H 'Authorization: Bearer ipa_sec_REPLACE_ME'

Click through your own site with that stream open, or watch the Live view in the admin app. See Quickstart for what the frames look like. A 204 with nothing on the stream means the batch validated to zero events; Limits and validation lists every silent drop.

What it does on its own

  • Ids. An anonymous id in both localStorage and a first-party cookie named ip_aid, each healing the other, plus a session id in ip_sid that rotates after 30 minutes idle. ip_aid is the same name the Shopify pixel and the Google Tag Manager tag use, so storefront, checkout and app events stitch into one visitor.
  • Entry context. utm_*, the landing path and the referrer host are captured once per session and attached to every event of that session, so attribution survives the second page.
  • Batching. Up to 20 events, 48 KB or 5 seconds, whichever comes first. The timer is armed only while the queue is non-empty, so an idle tab never wakes up, and there is no polling anywhere.
  • Unload. visibilitychange and pagehide flush through navigator.sendBeacon, so the last batch of a visit survives the tab closing.

Autocapture

Autocapture records common interactions with no instrumentation, under reserved names:

One delegated listener each for click, change and submit. Every captured element gets a deterministic selector and its visible text in the event's el field; input values are never read, [type=password] and [data-track-mask] are skipped entirely, and [data-track-ignore] or .ip-no-capture opts an element out. $rageclick is the one to look at first: it is the closest thing to a frustration signal that costs nothing to collect.

Autocapture is a convenience, not a substitute for naming the events that matter. A funnel built on $autocapture plus a selector breaks at the next redesign; one built on Signed Up does not. Defined events let you name an action after the fact from autocaptured data, retroactively, which is the usual way out of that trap.

Nothing in the browser sends until you decide it may.

const analytics = createAnalytics({
  token: 'ipa_pub_REPLACE_ME',
  consent: () => localStorage.getItem('cookie-consent') === 'granted',
});

analytics.setConsent(true);       // once the visitor agrees
analytics.setPaused(true);        // stop sending, keep the ids

With consent false, no ids are persisted and no session is recorded either, so refusing costs the visitor nothing. The tracker inside our own app passes a function that also refuses when navigator.doNotTrack is 1, when window.doNotTrack is 1, or when navigator.globalPrivacyControl is true; copy that rule if it matches your policy.

Bear in mind what a Project token can and cannot do: it can write events, and nothing else. It cannot read a report, list people or change a setting, so a leaked bundle is not a data-exposure incident. See Data and privacy.

Single-page apps

  • Call analytics.page() on the route change, not only on the first load. A history-based router fires no navigation event on its own.
  • Keep one client instance for the page's lifetime.
  • The SDK already flushes on pagehide rather than unload, because unload does not fire on mobile Safari. If you write your own client, do the same.

Without a dependency

Everything above is one JSON POST, so a small client of your own works too. Ids first:

const HOST = 'https://t.intelligent.page';
const TOKEN = 'ipa_pub_REPLACE_ME';

const uuid = () => crypto.randomUUID();
const anonId = localStorage.getItem('ip_aid') ?? (() => {
  const id = uuid();
  localStorage.setItem('ip_aid', id);
  return id;
})();
let userId = localStorage.getItem('ip_uid');

Then a queue and a flush:

let queue = [];

function track(name, props) {
  queue.push({
    id: uuid(),
    ts: new Date().toISOString(),
    event: name,
    aid: anonId,
    ...(userId ? { uid: userId } : {}),
    path: location.pathname,
    url: location.href,
    ref: document.referrer || undefined,
    tz: Intl.DateTimeFormat().resolvedOptions().timeZone,
    loc: navigator.language,
    props,
  });
  if (queue.length >= 20) flush();
}

async function flush() {
  if (!queue.length) return;
  const events = queue.splice(0, 50);
  await fetch(`${HOST}/v1/ingest`, {
    method: 'POST',
    headers: { 'content-type': 'application/json', 'x-analytics-token': TOKEN },
    body: JSON.stringify({ v: 1, sentAt: new Date().toISOString(), events }),
    keepalive: true,
  });
}

Send $pageview on load and on every route change, and $pageleave on unload, if you want the session and bounce numbers reports expect.

navigator.sendBeacon cannot set headers, which is why the token is also accepted in the request body:

addEventListener('pagehide', () => {
  if (!queue.length) return;
  const body = JSON.stringify({ v: 1, token: TOKEN, events: queue.splice(0, 50) });
  navigator.sendBeacon(`${HOST}/v1/ingest`, new Blob([body], { type: 'text/plain' }));
});

text/plain bodies are parsed as JSON for exactly this case.

Identity is one more route:

async function identify(id, traits) {
  userId = id;
  localStorage.setItem('ip_uid', id);
  await fetch(`${HOST}/v1/identify`, {
    method: 'POST',
    headers: { 'content-type': 'application/json', 'x-analytics-token': TOKEN },
    body: JSON.stringify({ distinctId: anonId, userId: id, traits }),
  });
}

Keep a flag in localStorage keyed on the anonId:userId pair so you call it once per sign-in, which is what our own client does. On sign-out, clear ip_uid and mint a fresh ip_aid.

Reference

Next