JavaScript SDK
@stancelens/js: one client for browsers, Node and edge runtimes, with batching, retries and an offline queue.
Use the npm package instead of the script tag when you want typed calls, consent handling, an offline queue, or the same client on the server. TypeScript, zero runtime dependencies, ESM and CommonJS.
Install from source
@stancelens/js isn't on npm yet. Build a tarball from the Stancelens repository with Bun, then install that file in your app:
# in a checkout of the Stancelens repository
cd stancelens/packages/js
bun install && bun run build && bun pm pack # writes stancelens-js-0.1.0.tgznpm install /path/to/stancelens/packages/js/stancelens-js-0.1.0.tgzQuick start
import { init, track, identify, flag } from "@stancelens/js";
init({ site: "SITE_ID", autoPageviews: true });
track("signup", { plan: "pro" });
identify("user_123", { plan: "pro" });
if ((await flag("new-checkout")) === "v2") showNewCheckout();The top-level functions use the shared client made by init(). Calls made before init() are queued (up to 1,000) and replayed in order. createClient() returns an independent client with the same methods.
On servers
On a server, pass an API key (owner or admin, from Account → API keys). Events then go to POST /api/v1/events, can be backfilled up to 30 days, and can carry the end user's User-Agent and IP. Pass a user per call, because a server has no single visitor:
import { createClient } from "@stancelens/js";
const stancelens = createClient({ site: "SITE_ID", apiKey: process.env.STANCELENS_API_KEY });
stancelens.track(
"invoice_paid",
{ amount: 49 },
{ userId: user.id, userAgent: req.headers["user-agent"] },
);
await stancelens.flush(); // before a serverless function returnsNever put an API key in browser code. The client logs a warning if you do.
API
| Function | What it does |
|---|---|
init(options) | Creates the shared client and returns it. Later calls return the same client and ignore their options. |
createClient(options) | A new, independent client. |
getClient() | The shared client, or null before init(). |
track(name, props?, options?) | Custom event. options: userId, anonymousId, timestamp, url, path, referrer, title, userAgent, ip (the last two with apiKey only). |
page(path?, props?, options?) | Page view. In browsers it defaults to the current URL; on servers, pass the path. |
identify(userId, traits?) | Links this browser's anonymous activity to userId and records traits. Repeating the same ID and traits sends nothing. identify(null) is reset(). |
reset() | Forgets the user ID and starts a new anonymous ID. Call it on logout. |
revenue(amount, currency = "USD", props?, name = "purchase", options?) | Event with revenue. options are the same as for track (userId, timestamp, …). |
flag(key) | Promise<boolean | string>: the flag's value for this user, false if off, unknown or on error. Records one $exposure per flag value, false included, so the control group is counted. Unknown keys and failed lookups record nothing. |
flags() | All flags, without exposure events. |
optOut(), optIn() | Consent. optOut() deletes unsent events and stops tracking on this device until optIn(). Both are remembered. |
flush() | Sends queued events now. Never rejects. |
Client-only methods: isOptedOut(), getAnonymousId(), getUserId(), getCachedFlags(), reloadFlags(), onFlags(listener) (returns an unsubscribe function), queueSize and shutdown() (flush, then remove timers and listeners).
Options
| Option | Default | |
|---|---|---|
site | required | Site ID. |
host | https://stancelens.com | Stancelens origin. |
endpoint | ${host}/api/event | Full ingest URL, e.g. a first-party proxy. |
apiKey | none | Server-side only: send to /api/v1/events with this key. |
autoPageviews | false | Browser: page view on init and on pushState, replaceState and back/forward when the URL changes. |
hash | false | Include #fragment in page URLs (with autoPageviews it also listens to hashchange). |
trackEngagement | true | Browser: send visible time per page as $engagement. |
flushAt | 20 | Send when this many events are queued (max 100 per request). |
flushInterval | 3000 | Send queued events at least this often (ms). |
maxQueueSize | 1000 | Unsent events kept; the oldest are dropped beyond it. |
maxRetries | 6 | Retries of a batch after 408, 429 or 5xx before it's dropped. |
storage | localStorage, else memory | "localStorage", "memory" or any { getItem, setItem, removeItem }. |
optOutByDefault | false | Start opted out until optIn() (consent banners). |
respectDnt | false | Treat Do Not Track and Global Privacy Control as opted out. |
platform | web in browsers, server elsewhere | One of web, ios, android, react-native, flutter, server. |
appVersion | none | Sent as app_version. |
flags | none | Flag values to use until the first response. |
flagsTtl | 300000 | How long fetched flags are reused (ms). |
fetch | globalThis.fetch | Custom fetch. |
debug | false | Log queueing, sends and failures to the console. |
disabled | false | Every call is a no-op; flag() resolves from flags or false. |
Delivery
- Never throws after construction. Invalid names, unserializable props and non-finite revenue are ignored (logged with
debug). Creating a client throws only withoutsite. - Batched: up to 100 events per request, after
flushInterval, atflushAt, or when the page is hidden or unloaded. Hidden and unload usenavigator.sendBeacon, falling back tofetchwithkeepalive. - Retries: 408, 429 and 5xx retry after 1 s, 2 s, 4 s… up to 60 s (±25% jitter,
Retry-Afterhonoured), at mostmaxRetriestimes. Other 4xx responses drop the batch. Network errors retry without a limit. - Offline queue: unsent events are stored (in
localStoragein browsers) and sent by the next page load or process, or when the browser goes back online. Each keeps its originalts; the server accepts events up to 72 hours old (30 days with an API key). Tabs share the queue without sending an event twice. - No duplicates: every event has a unique
id, so a retried copy the server already stored is dropped. Each request carriessent_atso the server can correct a device clock that's wrong. - Anonymous ID: a random UUID stored as
stancelens_vidand sent asvid; replaced only byreset()or by identifying a different user. No cookies. - Consent: opted out means nothing is queued or sent (flags still work, without exposures).
localStorage.stancelens_ignorealso opts a browser out, as with the script tag. - Flags: concurrent calls share one request; results are cached per user for
flagsTtland stored for the next load;identify()andreset()clear them. - Every event carries
platformandsdk: "stancelens-js/<version>".