Skip to main content

Affiliate Tracking JavaScript Reference

Configure the AffiliateBase tracking script, read generated referral IDs, and connect browser attribution to Stripe Checkout.

Table of Contents

Use this JavaScript reference to install AffiliateBase browser tracking, configure attribution parameters, read the generated referral ID, and hand that ID to Stripe Checkout.

The automatic installation uses one script tag with your existing data-account-id. Connect Stripe separately in AffiliateBase before verifying Stripe checkout attribution.

Install snippet

<script
  async
  src="https://app.affiliatebase.io/track.js"
  data-account-id="YOUR_ACCOUNT_ID"
></script>

This is all that automatic referral capture and supported checkout integrations need. If advanced code calls affiliatebase(...) before the remote script loads, add the preloader before the same script tag:

Advanced preloader

<script>
  (function (w, r) {
    w._abq = w._abq || [];
    w[r] =
      w[r] ||
      function () {
        (w[r].q = w[r].q || []).push(arguments);
      };
  })(window, "affiliatebase");
</script>
<script
  async
  src="https://app.affiliatebase.io/track.js"
  data-account-id="YOUR_ACCOUNT_ID"
></script>

Updates and exact-version installations

The default URL serves the approved stable build. Compatible updates arrive automatically on subsequent page loads after caches refresh. Publishing a numbered package does not automatically promote it to this URL. Breaking changes require an explicit migration.

For controlled upgrades, developers can install an exact npm package version or use a numbered jsDelivr URL. For example, https://cdn.jsdelivr.net/npm/@relay-capital/affiliatebase-tracking@1.0.10/dist/track.min.js remains the immutable 1.0.10 release; it will not receive later fixes automatically. Keep exact pins current yourself. Do not load both a bundled copy and the hosted script.

To migrate an existing tag, replace only its script URL with https://app.affiliatebase.io/track.js, preserving the queue snippet, account ID and other attributes. Permit app.affiliatebase.io in CSP script-src and connect-src. Keep your consent manager’s loading rules in place.

Installation diagnostics report the public account ID, loaded version and script source without URL queries/fragments, visitor identifiers or page paths. Requests omit credentials. Reporting works without a referral click and cannot create a referral, sale or commission. Diagnostic failure does not block attribution. Reports respect configured Do Not Track handling; data-telemetry="false" disables them. A missing report does not prove the script is absent.

Script attributes

AttributeRequiredNotes
data-account-idYesAccount id (data-account alias also supported)
data-api-urlNoOverride API base URL (useful for local dev)
data-debugNotrue enables client logs
data-telemetryNofalse disables installation diagnostic reporting
data-affiliatebase-paramsNoComma-separated custom attribution params
data-paramsNoAlias for data-affiliatebase-params
data-domainsNoOptional host hints to narrow cross-domain handoff destinations; only hosts already approved for the account are used
data-request-timeout-msNoRequest timeout (default 8000)
data-respect-dntNotrue skips tracking requests when DNT is enabled
data-cookie-domainNoValid parent domain for sharing attribution across sibling subdomains; host-only cookies are the default
data-memberstackNoSet to false to disable automatic Memberstack checkout metadata wiring
data-memberstack-timeout-msNoMaximum Memberstack attribution wait in milliseconds (default 1500)
data-telemetryNoSet to false to disable installation diagnostics

Approved hosts and browser state

In Setup or Settings, use Approved site or app hosts under Tracking domains to add the first-party hosts that may receive attribution. Enter hostnames only, one per line, without a scheme or path. AffiliateBase returns this account-approved list from /api/track and uses it when preparing links across your own sites or apps. The tracker refreshes the approved hosts and handoff configuration during page load and when the page regains focus, so a settings change does not require a new snippet.

The standard script tag does not need a manually supplied data-domains value. If you provide data-domains, or a per-link data-domains hint, it can narrow the account-approved hosts used for that link; it cannot authorize an arbitrary host or a third-party checkout page.

Cookies are host-only by default. Set data-cookie-domain only to a valid parent domain when sibling subdomains must share the cookie. Attribution in browser storage is account-scoped, so a referral saved for one AffiliateBase account is not used by another account on the same browser.

Same-referral cross-domain handoff

When a referred visitor follows a link to another account-approved first-party host, the tracker requests a short-lived encrypted ab_handoff capability and adds it to that link automatically. The capability is bound to the account, source host, destination host, selected referral, and existing visitor session. The destination redeems it to restore the same referral UUID, visitor session, and original referral expiry; redemption never creates a new referral or visitor session. The reserved parameter is removed promptly after processing.

The handoff is fail-closed. An invalid, expired, or no-longer-approved capability produces no new attribution, while the destination page and checkout continue normally. Retrying a still-valid capability is safe and restores the same selected referral/session without creating another referral. Existing valid destination attribution remains selected. The tracker preserves merchant-owned via, referral, and coupon query values and hash fragments.

Do not construct ab_handoff URLs yourself or use an account ID or public referral UUID to create one. The tracker can request a capability only when the current visitor has a matching referral and visitor-session proof. Third-party checkout pages still use their provider-specific or server-side integration; this handoff covers merchant-approved first-party hosts.

URL parameter behavior

Priority:

  1. ?ab_handoff=<CAPABILITY> (redeems an approved-domain same-referral handoff)
  2. ?referral=<REFERRAL_ID> (preloads an existing referral id)
  3. ?via=<TOKEN> (canonical token parameter)
  4. Custom params from data-affiliatebase-params (for example ?partner=<TOKEN>)

ab_handoff is a reserved, short-lived capability. A bare account ID or public referral UUID cannot mint one; a matching existing visitor-session proof is required.

Runtime methods

// Identify a referred signup; no sale or commission is created.
affiliatebase("convert", { email: "customer@example.com" });
affiliatebase("identify", { email: "customer@example.com" }); // alias

affiliatebase("source", "affiliate_token");
affiliatebase("track", "affiliate_token"); // alias

affiliatebase("ready", () => console.log("attribution settled"));

affiliatebase("debug", true);
affiliatebase("set_debug", true); // alias

affiliatebase("reset");
affiliatebase("clear"); // alias

affiliatebase("referral"); // returns referral id
affiliatebase("tracked"); // returns whether attribution tracking completed
affiliatebase("state"); // returns full attribution state

Identity, readiness, and reset

Browser identify, convert, and conversion associate an email with the current referral and visitor session through /api/track/lead. They do not record revenue. Use Stripe webhooks for purchases.

affiliatebase("ready", async () => {
  const result = await affiliatebase("identify", { email: "customer@example.com" });
  if (!result.success) console.log(result.code);
});

ready waits until pending attribution requests finish, including failures. A ready callback can run without a referral: check window.AffiliateBase.referral before using it. Preloader calls are queued and have no immediate result; await identity inside a ready callback after the library loads.

After attribution settles, affiliatebase("state") exposes attribution.status as none, pending, succeeded, failed, or blocked, together with a reason when available. The loaded global also exposes window.AffiliateBase.whenAttributionReady(), which resolves to this structured result:

const attribution = await window.AffiliateBase.whenAttributionReady();
if (attribution.status === "succeeded" && attribution.referral) {
  // Pass the generated referral ID to your checkout request.
}

Automatic checkout integrations must remain usable when tracking is blocked, unavailable, or times out. Continue checkout without referral metadata when the current tracking attempt does not produce a referral.

Identity returns a Promise with success, optional attributed, and an error code when unsuccessful. Common codes include NO_REFERRAL, EMAIL_REQUIRED, DO_NOT_TRACK, REQUEST_FAILED, and SERVER_CONVERSION_REQUIRED. Amount, currency, order, and payment fields are rejected in browser calls.

reset clears browser attribution and restores values the tracker inserted into forms, links, and Stripe components. It preserves subsequent merchant edits and invalidates earlier in-flight attribution responses. It does not delete server records or revoke commissions.

Signed server conversions

Most Stripe integrations should use automatic verified webhooks. The advanced endpoint POST https://app.affiliatebase.io/api/track/convert can attribute an existing verified Stripe sale; it is not an API for arbitrary offline or non-Stripe revenue.

Keep the API token on your server. The key must belong to the referral’s account and grant tracking.conversions.write (or full access). MCP reporting tokens cannot use this endpoint. Sign the exact JSON bytes sent, using a current Unix timestamp and a fresh nonce for every request. Requests outside the five-minute window and reused nonces are rejected.

// Node.js server only. Values come from your verified checkout records.
import { createHash, createHmac, randomUUID } from "node:crypto";

async function attributeVerifiedSale({ referralId, visitorId, email, paymentIntentId, amountCents, currency, conversionId }) {
  const token = process.env.AFFILIATEBASE_API_KEY;
  if (!token) throw new Error("Missing server API key");
  const body = JSON.stringify({
    referral_id: referralId,
    visitor_id: visitorId,
    email,
    amount_cents: amountCents,
    currency,
    conversion_id: conversionId,
    stripe_payment_intent_id: paymentIntentId,
  });
  const timestamp = Math.floor(Date.now() / 1000).toString();
  const nonce = randomUUID();
  const digest = createHash("sha256").update(body).digest("hex");
  const signature = createHmac("sha256", token)
    .update([timestamp, nonce, digest].join(".")).digest("hex");
  const response = await fetch("https://app.affiliatebase.io/api/track/convert", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      "X-Track-Timestamp": timestamp,
      "X-Track-Nonce": nonce,
      "X-Track-Signature": signature,
    },
    body,
  });
  const result = await response.json();
  if (!response.ok || !result.success) throw new Error(result.code || result.error);
  return result;
}

Use integer cents, an explicit currency, a stable conversion ID, and the generated referral ID. Supply a verified Stripe invoice, payment intent, or charge reference using stripe_invoice_id, stripe_payment_intent_id, or stripe_charge_id. The payment must already exist in AffiliateBase and match its recorded amount and currency. A valid signature does not bypass payment, visitor, attribution, or duplicate checks. On retry, keep the conversion ID and use a fresh timestamp, nonce, and signature.

Global state

window.AffiliateBase.referral;
window.AffiliateBase.affiliate;
window.AffiliateBase.campaign;
window.AffiliateBase.coupon;
window.AffiliateBase.tracked;
window.AffiliateBase.version;

window.affiliatebase_referral; // legacy alias getter

Use window.AffiliateBase.referral or affiliatebase("state") for new integrations. The legacy alias remains available for older snippets, but new Stripe Checkout code should submit the generated window.AffiliateBase.referral value to your server.

Automatic integrations

Forms

Add data-affiliatebase to a form to auto-inject a hidden referral input when attribution exists. If the active referral includes an AffiliateBase coupon, the script also injects a hidden coupon input.

<form data-affiliatebase action="/signup" method="POST">
  ...
</form>

Optional custom hidden field name:

<form data-affiliatebase data-affiliatebase-param-name="referral_id">
  ...
</form>

Stripe Buy Buttons and Pricing Tables

The script sets client-reference-id on standard Stripe Buy Button and Pricing Table elements after a referred visitor is present.

<stripe-buy-button buy-button-id="buy_btn_xxx" publishable-key="pk_live_xxx"></stripe-buy-button>
<stripe-pricing-table pricing-table-id="prctbl_xxx" publishable-key="pk_live_xxx"></stripe-pricing-table>

For standard https://buy.stripe.com/... and https://link.payment/... links, the script appends client_reference_id=<generated_referral_id> after a referred visitor is present. For custom Stripe-hosted or redirected Payment Link URLs, add data-affiliatebase to the anchor as an explicit opt-in where AffiliateBase owns client_reference_id.

<a href="https://buy.stripe.com/...">Buy</a>

<a data-affiliatebase href="https://link.payment/...">Buy</a>

Memberstack DOM checkout

AffiliateBase provides an automatic adapter for Memberstack’s DOM checkout. For setup steps, see the Memberstack guide.

When Memberstack’s DOM SDK is present, the tracker automatically wraps purchasePlansWithCheckout. A confirmed referral adds the generated referral UUID as metadataForCheckout.affiliatebase_referral_id. The wrapper preserves the original options, caller metadata, receiver, and checkout behavior. It waits up to 1500 milliseconds by default for attribution, then calls the original checkout without a referral when attribution is none, failed, blocked, or timed out.

Memberstack detection is automatic; no second AffiliateBase tag or custom checkout handler is required. Set data-memberstack="false" when checkout metadata is managed separately. Existing affiliatebase_referral_id, referral_id, referralId, or referral metadata is preserved; conflicting values are reported in diagnostics rather than overwritten.

Cross-domain and first-party continuity

The standard script uses the account-approved host list returned by /api/track. With data-domains="example.com,checkout.example.com", matching links are narrowed to those hosts; the attribute cannot authorize an arbitrary host or a third-party checkout page. For an approved cross-domain link, the tracker carries the current referral and visitor session through the encrypted ab_handoff capability described above. Tracker-owned values follow later attribution changes, while merchant-owned query values and hashes are preserved.

Browser events

  • AffiliateBase.initialized
  • AffiliateBase.tracked
  • AffiliateBase.reset
  • AffiliateBase.identified (successful lead handoff)
  • AffiliateBase.error (identity failure; inspect event.detail.code)

Example:

window.addEventListener("AffiliateBase.tracked", (event) => {
  console.log(event.detail.referral);
});

Local development

Point the script at your local API:

<script
  async
  src="/track.js"
  data-account-id="YOUR_ACCOUNT_ID"
  data-api-url="http://localhost:3000"
  data-debug="true"
></script>