Documentation sections

Install the SDK

The browser SDK is dependency-free and ships in two builds: an IIFE served at /sdk.js that self-initializes from a data-key attribute, and an ESM build for bundlers. The dependency-free SDK has a build gate that fails if it crosses 10KB gzipped.

Replace bl_your_write_key in an example with the public write key from Setup → Your write key in your project. The examples send events to https://betterloopai.com.

Script tag (any site)

Put it anywhere in the document. It is async, so it never blocks rendering, and it starts by recording the current pageview.

<script async src="https://betterloopai.com/sdk.js" data-key="bl_your_write_key"></script>
AttributeBehaviour
data-capture-textoptionalSet to "true" to opt in to text capture. Off by default; audit for personal data first.
data-exclude-pathsoptionalComma-separated path prefixes to exclude from all collection.
data-exclude-selectorsoptionalComma-separated selectors whose click targets are ignored.
data-keyrequiredThe project write key.
data-endpointoptionalOverride the ingest URL. Defaults to /api/ingest resolved against the script src, so the default is correct whenever you load sdk.js from your Betterloop instance.
data-debugoptionalSet to "true" to log events to the console.

The script-tag build always respects Do Not Track and Global Privacy Control - there is no data attribute to turn that off. Only the npm build exposes respectDNT.

npm / ESM

Install the versioned Betterloop SDK package in your app directory.

npm install https://betterloopai.com/sdk/betterloop-sdk-0.1.1.tgz

Call init() once in your browser entry point.

import { init } from "@betterloop/sdk";

init({
  key: "bl_your_write_key",
  endpoint: "https://betterloopai.com/api/ingest",
});

Always pass endpoint on this build. Its compiled-in default points at https://betterloopai.com/api/ingest, which is only correct once that domain is the instance you actually use.

Exports

ExportSignatureNotes
initinit(options)Idempotent - a second call while running is a no-op. Records the first pageview and installs every hook.
tracktrack(name, attrs?)Custom event. Name is truncated to 80 characters. Names starting with $ are reserved.
shutdownshutdown()Flushes with sendBeacon, removes every listener, disconnects the observers, and restores the patched history methods. Safe to call in an effect cleanup. For consent withdrawal, call shutdown({discard: true}) to discard unsent events.
autoInitautoInit()Used by the script-tag build to read the data attributes off its own tag. You do not normally call this yourself.

init options

OptionTypeDefaultBehaviour
captureTextbooleanfalseOpt in to page titles, click labels and detailed errors only after auditing them for personal data. Pattern redaction is not a guarantee of anonymity.
includePathsstring[][]Optional exact pathname allowlist, enforced inside every collector and during SPA navigation. Empty keeps the normal all-path behavior.
excludePathsstring[][]Path prefixes and their descendants on which no events, including custom events, are collected.
excludeSelectorsstring[][]Ignore clicks inside matching elements. Form controls, editable fields and data-private/data-betterloop-ignore elements are always ignored.
keystringrequiredYour project write key (starts with bl_). Public by design, like any analytics key. init() returns silently if it is missing.
endpointstringhttps://betterloopai.com/api/ingestWhere batches are POSTed. The script-tag build derives this from its own src, so you only set it on the npm build.
debugbooleanfalseLogs captured events and rejected HTTP batches to the console with a [betterloop] prefix.
respectDNTbooleantrueWhen true, init() collects nothing if navigator.doNotTrack is "1" or Global Privacy Control is on.

React (Vite, CRA, anything bundled)

Initialize once at module scope in your entry file, outside the component tree. Nothing else is needed: React Router and every other client router go through history.pushState, which the SDK hooks.

// Browser entry file (src/main.tsx in Vite, src/index.tsx in Create React App)
import { createRoot } from "react-dom/client";
import { init } from "@betterloop/sdk";
import App from "./App";

init({
  key: "bl_your_write_key",
  endpoint: "https://betterloopai.com/api/ingest",
});

createRoot(document.getElementById("root")!).render(<App />);

Next.js (App Router)

Check deployed Next.js redirects

The simplest route is next/script in the root layout. Extra props are forwarded to the tag, so the data attributes work exactly as they do in plain HTML, and the layout stays a server component.

// app/layout.tsx
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script
          src="https://betterloopai.com/sdk.js"
          data-key="bl_your_write_key"
          strategy="afterInteractive"
        />
      </body>
    </html>
  );
}

If you would rather bundle the SDK, wrap it in a small client component. Render it once inside <body> in the root layout - the cleanup call keeps React Strict Mode's double-invoke in development from leaving stale listeners behind.

// app/betterloop.tsx
"use client";

import { useEffect } from "react";
import { init, shutdown } from "@betterloop/sdk";

export default function Betterloop() {
  useEffect(() => {
    init({
      key: "bl_your_write_key",
      endpoint: "https://betterloopai.com/api/ingest",
    });
    return () => shutdown();
  }, []);
  return null;
}

// app/layout.tsx - add this import, then render <Betterloop /> inside <body>
// import Betterloop from "./betterloop";

Vue

Same shape: init before mount. Vue Router navigations are captured through the history hooks, so there is no router guard to register.

// src/main.ts
import { createApp } from "vue";
import { init } from "@betterloop/sdk";
import App from "./App.vue";

init({
  key: "bl_your_write_key",
  endpoint: "https://betterloopai.com/api/ingest",
});

createApp(App).mount("#app");

SPA behaviour

  • Routing. pushState, replaceState, and popstate are all hooked. A pageview fires when pathname changes. Common identifiers are redacted in the recorded path.
  • Query-string state. A navigation that keeps the same pathname (search-as-you-type or filter syncing) does not emit a pageview. Query strings and fragments are not collected.
  • Time on page. Leaving a route emits a custom event named $time_on_page with the previous path and its duration in milliseconds. The same event fires when the tab is hidden.
  • Sessions. The session id is 16 hex characters from crypto.getRandomValues, stored in sessionStorage under _fp_sid - still the pre-rename name on purpose, because renaming it would orphan every session already in a visitor's browser. It is per tab, and it is not a cookie. If sessionStorage throws (private modes, blocked storage) the id lives in memory for the page instead.
  • Teardown. Call shutdown() in micro-frontend or module-federation setups where your bundle can be unmounted, and on hot reload if your dev setup re-executes the entry file.

Batching and transport

  • Events queue in memory and flush every 5 seconds, or immediately at 50 queued events.
  • On visibilitychange to hidden and on pagehide, the SDK uses navigator.sendBeacon to queue delivery during unload. If the browser rejects the beacon, the SDK falls back to fetch with keepalive.
  • A network error puts the batch back for the next flush. The retry backlog holds up to 100 events and drops the oldest first. An HTTP response ends that attempt.
  • Requests are plain application/json POSTs. The ingest endpoint answers CORS preflights and accepts any origin unless you configure an allowlist in project settings.

Monthly event allowance

An ingest response of 402 quota_exceeded means the whole batch would go over the project's monthly event allowance. The response includes the next reset in reset_at and a billing_url to review your plan. Open the project dashboard to see the remaining events.

When the SDK receives a 402 from the default hosted endpoint, it shows a Billing link in the browser's developer console, even with debug mode off.

A custom collector can send a smaller batch that fits the remaining allowance. The allowance resets at the start of the next UTC calendar month.

Compare event allowances and plans

Custom events

// script tag build - Betterloop is a global
Betterloop.track("signup_completed", { plan: "free", source: "pricing" });

// npm build
import { track } from "@betterloop/sdk";
track("signup_completed", { plan: "free", source: "pricing" });

Attributes are stored as JSON on the event and must serialize to 8192 bytes or less, otherwise ingest rejects the whole batch with 400 invalid_payload. Do not put personal data in there - see Privacy and data.

See custom event counts

Verify the install

Set up monitoring

Get the install snippet for one Free project. If your project is waiting for its first event, Setup offers a copyable test page when its origin policy can allow localhost. Sign in to use an existing project.

Get help with setup
  1. Open your project's Setup tab. It checks for events and shows Connected after one arrives.
  2. Add data-debug="true" (or debug: true with SDK 0.1.1 or newer for npm). Keep the site tab visible and wait for a batch. In the console, [betterloop] ingest rejected gives the HTTP status and a next step.
  3. Check the network tab for a POST to /api/ingest. A 200 with {ok: true} means it landed.

Seeing no POST? Do Not Track and Global Privacy Control stop collection. A browser content blocker can also prevent the request. Check the Network tab for blocked requests.

  • HTTP 401 means the key is unknown. Copy the current write key from Setup.
  • For HTTP 402, check the monthly event allowance.
  • For HTTP 403, add the site's exact origin to Allowed origins in project Settings.
  • For HTTP 429, check for duplicate installs or too many custom events.

The full error list is in the API reference.