# Tracker JavaScript API

> Every option and command the Supametrics tracking script supports, with copy-paste examples.

Source: https://supametrics.io/docs/tracker-javascript-api

The tracking script (`ax.js`) records pageviews on its own. This page lists everything else it can do: the
attributes you can put on the script tag, and the commands your own code can send through
`window.analyticsx`. For a first install, start with [Install and verify the script](https://supametrics.io/docs/install-the-script).

## The script tag

```html
<script defer data-site="YOUR_SITE_ID" src="https://app.supametrics.io/js/ax.js"></script>
```

Copy the exact snippet, with your site ID filled in, from **Site settings › General** (or the **Setup**
screen before your site is verified). Put it inside `<head>` on every page.

Without `data-site` the script does nothing.

## Script tag attributes

| Attribute | Default | What it does |
|---|---|---|
| `data-site="..."` | required | Your website's public site ID. |
| `data-consent="required"` | off | Sends nothing and sets no cookies until your code calls `analyticsx('consent', true)`. See [Consent](#consent). |
| `data-domain="example.com"` | detected | The domain the visitor cookies are set on. By default the script picks your root domain, so `example.com` and `app.example.com` share one visitor. Set this only if detection picks the wrong one. |
| `data-api="https://..."` | `https://app.supametrics.io/api/event` | Where events are sent. Use it when you proxy tracking through your own domain. |
| `data-allow-localhost` | off | Also track on local development hosts (see [Local development](#local-development)). |

> **Note:** When the `data-api` address ends in `/event`, the script also loads its click-goal settings
> through your proxy, from the same address with `/event` replaced by `/config/<site ID>`; forward that
> `GET` to `https://app.supametrics.io/api/config/<site ID>`. If the proxy doesn't answer it, or the address
> ends differently, the settings load from the address the script came from (`<script src>` origin +
> `/api/config/<site ID>`).

## The analyticsx command function

Once the script has loaded, `window.analyticsx` is a function. Its first argument is a command name:

| Command | Example | What it does |
|---|---|---|
| `track` | `analyticsx('track', 'signup')` | Sends a custom event. |
| `identify` | `analyticsx('identify', { id, email, name })` | Attaches your own user to this visitor. |
| `visitorId` | `analyticsx('visitorId')` | Returns this visitor's ID (a string), or `null`. |
| `pageview` | `analyticsx('pageview')` | Sends a pageview for the current address right now. |
| `consent` | `analyticsx('consent', true)` | Grants (`true`) or withdraws (`false`) consent. |

Unknown commands are ignored. Always call it as `window.analyticsx?.(...)` so your page does not break if
the script is blocked or has not loaded yet (see [When the script is blocked](#when-the-script-is-blocked)).

## Custom events

```js
window.analyticsx?.('track', 'signup');
window.analyticsx?.('track', 'Started trial (Pro)');
```

- The name is any text. Spaces and punctuation are allowed. It is cut to **64 characters**.
- Events carry a name only. Extra properties (an object as the third argument) are not supported and are
  ignored.
- A custom event is stored only when it completes a goal of type **JavaScript event** with exactly the same
  name. Create the goal on the **Goals** screen; see [Goals](https://supametrics.io/docs/goals#javascript-event).
- An event name that matches no goal is not stored as a completion, but Supametrics remembers the name so the
  **Goals** screen can offer to turn it into a goal.
- Events are sent with `navigator.sendBeacon` when the browser has it, so a `track` call right before a page
  navigation still arrives.

Call `track` after the thing has actually happened, for example after your signup request succeeds:

```js
const res = await fetch('/api/signup', { method: 'POST', body: form });
if (res.ok) window.analyticsx?.('track', 'signup');
```

## Identify signed-in users

```js
window.analyticsx?.('identify', { id: user.id, email: user.email, name: user.name });
```

| Field | Limit | Notes |
|---|---|---|
| `id` | 128 characters | Your own user ID. Numbers are turned into text. |
| `email` | 254 characters | Must be a valid email address. Stored in lower case. |
| `name` | 128 characters | Display name. |

- All three fields are optional, but at least one must be present or nothing is sent. Empty strings and
  `null` count as missing.
- Later calls fill in fields without clearing earlier ones: `identify({ id })` keeps an email sent before.
- An invalid email makes the whole identify request fail, so the id and name in the same call are not
  saved either. Leave `email` out if you are not sure it is valid.
- The name or email then shows on the **Visitors** screen, where you can search by it and erase a person.
  See [Visitors and visitor profiles](https://supametrics.io/docs/visitors).
- Call it on every login, so each browser the person uses is linked to them.

This is personal data. Mention it in your privacy policy. With `data-consent="required"`, identify is only
sent after consent.

## Visitor ID for Stripe

```js
const visitorId = window.analyticsx?.('visitorId'); // a string, or null/undefined
```

Pass this into your Stripe Checkout session metadata as `ax_visitor_id` so the payment is credited to the
visit that brought the customer. It returns `null` when the visitor is excluded or has not given consent
(with `data-consent="required"`), and `undefined` if the script is blocked. Full steps:
[Connect Stripe](https://supametrics.io/docs/connect-stripe).

## Consent

With `data-consent="required"` on the script tag, nothing is sent and no cookies are set until you call:

```js
window.analyticsx?.('consent', true);  // visitor accepted: the first pageview is sent now
window.analyticsx?.('consent', false); // visitor withdrew: tracking stops and the cookies are removed
```

The choice is saved in the visitor's browser (`localStorage`), so you only need to call it when the visitor
makes or changes a choice. Without `data-consent="required"`, `consent` calls have no visible effect.

## Single-page apps

Apps that change the address with the History API (Next.js, React Router, Vue Router, SvelteKit and most
other routers) are tracked automatically:

- Every `history.pushState` and `history.replaceState` call, and the back and forward buttons
  (`popstate`), send a pageview for the new address.
- A pageview is only sent when the path or query string actually changes. Calling `replaceState` with the
  same address does not count twice.
- The referrer is sent with the first pageview of the page load only.

To force a pageview yourself (for example after a route change your router does without the History API):

```js
window.analyticsx?.('pageview');
```

### Hash routing

Changes to the `#hash` part of the address are not tracked. Pages are recorded by path, so in an app that
routes with hashes (`/#/settings`, `/#/billing`) every screen is recorded as the same page (`/`). Switch the
router to History API mode (for example `createWebHistory` in Vue Router or `BrowserRouter` in React Router)
to see each screen as its own page.

## Exit links

Clicks on links to other websites are recorded as exit links, shown under **Details › Pages › Exit links**.
Nothing to set up:

- Left clicks and middle clicks on `http` and `https` links count.
- Links to your own domain and its subdomains are not exit links.
- Only the link's origin and path are sent (`https://partner.com/page`), never its query string. At most
  1,000 characters.
- Exit links don't count toward your plan's events.

## Click goals

Goals of type **Element click** are configured on the **Goals** screen with a CSS selector. The script
downloads your click goals when the page loads (cached for up to a minute per browser tab) and sends a
completion when a visitor clicks a matching element or anything inside it. No code is needed. See
[Goals](https://supametrics.io/docs/goals#element-click).

## Exclude your own visits

Open any page of your site with `?ax_ignore=true` at the end of the address:

```
https://example.com/?ax_ignore=true
```

That browser is never tracked again: the script stops completely, and `analyticsx('visitorId')` returns
`null`. Undo it with `?ax_ignore=false`. Do this once in each browser you use. **Site settings ›
Exclusions** has a button that opens this link for you, and can also exclude by IP address, page or country;
see [Exclusions](https://supametrics.io/docs/exclusions).

## Local development

By default the script does nothing on local hosts: `localhost`, `127.x.x.x`, `0.0.0.0`, `[::1]`, any name
ending in `.local`, and pages opened from a file. To test tracking locally, add `data-allow-localhost`:

```html
<script defer data-site="YOUR_SITE_ID" data-allow-localhost src="https://app.supametrics.io/js/ax.js"></script>
```

Those visits are stored under their hostname (for example `localhost`). Remove the attribute before you
deploy, or drop that hostname later in **Site settings › Exclusions**.

The script also does nothing in automated browsers (when `navigator.webdriver` is set), so end-to-end test
runs are not counted.

## When the script is blocked

If an ad blocker blocks the script, or it fails to load, `window.analyticsx` is never defined. Calls written
as `window.analyticsx?.(...)` then do nothing and your page keeps working. Calls written as
`window.analyticsx(...)` throw an error.

If your code may run before the script has loaded (the script uses `defer`), you can add a small queue in
front of the snippet. Calls made before the script loads are kept and run once it starts:

```html
<script>
  window.analyticsx = window.analyticsx || function () {
    (window.analyticsx.q = window.analyticsx.q || []).push(arguments);
  };
</script>
<script defer data-site="YOUR_SITE_ID" src="https://app.supametrics.io/js/ax.js"></script>
```

With the queue in place, `track`, `identify`, `pageview` and `consent` calls are replayed in order.
`visitorId` cannot return a value from the queue; call it after the page has loaded.

> **Note:** with the queue, `window.analyticsx` always exists, so if the script is blocked your queued calls
> simply never send.

## What the script sends

- Personal parameters in the page address (`email`, `e-mail`, `name`, `phone`, `password`, `pass`,
  `token`, `access_token`, `id_token`, `auth`, `code`, `secret`, `key`, `api_key`, `license_key`,
  `license`, in any letter case) are removed in the browser before anything is sent.
- Each event has its own ID, so a request the browser retries is stored once.
- Page addresses longer than 2,000 characters are rejected by the server, and so is any request over 8 KB.
- Requests use `text/plain` and send no cookies to Supametrics, so there is no CORS preflight.
- Bots are ignored on the server (see [Bots and AI crawlers](https://supametrics.io/docs/bot-tracking)).

Cookies and storage the script uses, all on your own domain:

| Name | Where | Lifetime | Purpose |
|---|---|---|---|
| `ax_vid` | cookie | 1 year | Visitor ID |
| `ax_sid` | cookie | 30 minutes, renewed on each event | Visit (session) ID |
| `ax_ignore` | localStorage | until removed | Set by `?ax_ignore=true` |
| `ax_consent` | localStorage | until withdrawn | Consent given |
| `ax_goals_<site ID>` | sessionStorage | 1 minute | Cached click goals |

For what is collected and why, see [What Supametrics collects](https://supametrics.io/docs/how-tracking-works).

## Moving from DataFast

`window.datafast` takes DataFast's call style, so goal code written for DataFast keeps working:

- `datafast('signup')` tracks the event `signup`, like `analyticsx('track', 'signup')`.
- `datafast('identify', { user_id, email, name })` identifies the visitor, like `analyticsx('identify', { id, email, name })`.

Calls queued before the script loaded are sent once it has. To bring your DataFast history too, see
[Import from DataFast](https://supametrics.io/docs/import-from-datafast).

## Installed as DataFaster

Supametrics used to be called DataFaster. Sites installed before the rename keep working unchanged:

- `/js/df.js` serves the same script as `/js/ax.js`.
- `window.datafaster` is the same function as `window.analyticsx`, with the same commands.
- `?df_ignore=true` still excludes a browser, like `?ax_ignore=true`.
- Old `df_vid` and `df_sid` cookies (and saved `df_` settings) are moved to the `ax_` names on the first
  visit, so returning visitors keep their ID.

Switch to the `ax.js` snippet and `window.analyticsx` whenever convenient.
