@lib-acr/browser
v0.0.3
Published
ACR SDK for browsers: JavaScript errors, page views, fetch timing, web vitals and sessions. Uses publishable keys only.
Readme
@lib-acr/browser
Browser SDK: uncaught errors and unhandled rejections, page views (including client-side route changes), fetch timing, Core Web Vitals, sessions and anonymous visitor ids. It accepts publishable keys only and refuses a secret key.
Install
npm install @lib-acr/browserQuick start
import { BrowserACR } from '@lib-acr/browser';
const acr = new BrowserACR({
apiKey: 'acr_live_…', // publishable key, restricted to your origins
endpoint: 'https://acr.example.com/v1',
appVersion: '2.3.0',
});
acr.start(); // installs listeners; call once
acr.identify('user_42'); // user id only; do not pass personal data
acr.trackEvent('product_added_to_cart', { productId: '123', price: 500 });
if (userSaysNo) acr.optOut(); // remembered on this browser; unsent telemetry is discarded
onLogout(() => acr.reset()); // new anonymous id and session, no user idOptions
| Option | Default | Notes |
|---|---|---|
| minLogLevel | warn | Logs below this level are dropped in the page |
| activePingMinutes | 5 | Sends acr.active at this interval while the tab is visible, so ACR can count live visitors. 0 turns it off |
| persistQueue | true | Keeps unsent telemetry (at most 200 items / 50 kB) in localStorage['acr.queue'] when the page is hidden and sends it on the next start() |
| sessionTimeoutMinutes | 30 | Any tracked event, log or error counts as activity; after the timeout a new session starts with its own session_start |
| trackErrors, trackPageViews, trackFetch, trackWebVitals | true | Automatic collection |
| respectDoNotTrack | true | |
| ui | true | Built-in maintenance screen, announcement banner and update prompt. false, or { maintenance?, announcement?, release? } to turn parts off |
| remoteControl | true | Poll the control snapshot (kill switch, maintenance, flags, commands) |
| configPollIntervalMs | 60000 | Control snapshot poll interval, at least 15 000 |
sampleRate is applied per session, so a sampled-in visitor is recorded completely.
Page hide and offline
On pagehide and when the tab becomes hidden, every kind is sent at once with fetch(…, { keepalive: true }), each
request at most 60 kB. navigator.sendBeacon is not used because it cannot send the API key header. A bounded copy of
anything still undelivered is kept in localStorage and replayed on the next visit; items keep their ids, so the API
drops duplicates.
Entry point
This package re-exports the shared types and helpers of @lib-acr/core (for example Attributes, LogLevel,
redactAttributes), but not AcrClient, HttpTransport or resolveConfig: those accept a secret key and do not
belong in browser code.
Notes
Query strings and fragments are never recorded, and numeric or UUID path segments become :id. Do Not Track is respected by default. A failed fetch that the app does not catch is reported once (as a network error), not again as an unhandled rejection. INP is reported as the maximum interaction duration, which is an approximation of the official metric. Request and response bodies and headers are never read.
Remote control
After start() the SDK polls the control snapshot (see @lib-acr/core) and polls again whenever the tab becomes
visible or the device comes back online. It acts on the snapshot as follows:
- Kill switch (
sdk.enabled: false) stops collection and flushing until it is lifted. - Maintenance: shows a full-page maintenance screen (focus-trapped dialog with a "Check again" button). Users or
anonymous ids in
allowUserIdsare exempt. - Announcement: a banner at the top while inside its
startsAt–endsAtwindow. Dismissals are remembered per id inlocalStorage['acr.dismissed']. Callacr.dismissAnnouncement(id)from your own UI. - Release: when
appVersionis belowlatestVersionorminimumVersion, a "new version available" prompt with a Reload button appears. Withmode: "force"and a version belowminimumVersion, the page reloads once per tab and minimum version (guarded insessionStorage['acr.forceReload']), then falls back to the prompt. - Commands run at most once per browser. Applied ids are kept in
localStorage['acr.cmds'](the last 50). Commands issued beforelocalStorage['acr.firstSeen']are skipped, and so are expired ones. The id is recorded before the SDK acts, then it sendsacr.command_applied(commandId,type,result,cleared) and flushes before any reload.clear_cacheclears the selected categories: Cache Storage, service workers,localStorageandsessionStorage(every key except the SDK's ownacr.*keys), IndexedDB (whereindexedDB.databases()exists, otherwise the result ispartial) and cookies readable by script. HttpOnly cookies cannot be cleared by any script.reloadwithmode: "immediate"reloads the page;mode: "prompt"shows the reload prompt. A second SDK-triggered reload within 30 s turns into a prompt, so reloads cannot loop.
The built-in UI is rendered inside the shadow root of one <acr-ui> element, so page styles do not affect it. It
follows prefers-color-scheme and inserts server text as text, never as HTML. To render your own UI:
const acr = new BrowserACR({ apiKey, endpoint, appVersion: '2.3.0', ui: { announcement: false } }); // or ui: false
acr.onControlChange(({ maintenance, announcement, release, reloadRequested }) => { /* render */ });remoteControl: false turns all of this off; configPollIntervalMs changes the poll interval.
Feature flags
if (acr.flag('new-checkout', false)) showNewCheckout();Flags are evaluated locally for the identified user, or for the anonymous id before identify(), so the same browser
keeps the same variant. They return the fallback until the first snapshot arrives.
Targeting. Rules can match country (resolved by the API for each config request), browser, os,
deviceType, language (read once in start()), appVersion, userId, anonymousId and your own attributes:
acr.identify('user_42', { plan: 'pro' }); // or acr.setAttributes({ plan: 'pro', beta: true }); null removes one
acr.getAttributes(); // what the rules see right nowAttributes stay in the page: they are used for local evaluation only. reset() clears them.
Variants and experiments.
switch (acr.flagVariant('checkout-experiment')) {
case 'one-page': renderOnePage(); break;
default: renderClassic();
}
acr.getFlagDetail('checkout-experiment'); // { value, variant, reason, ruleId? }, handy for debuggingFor flags with trackExposure (an experiment is running), the first flag(), flagVariant() or getFlagDetail() per
session and variant sends acr.flag_exposure. Sent exposures are remembered in sessionStorage['acr.exposures'], so
re-renders and reloads of the tab do not repeat them. Nothing is sent after opt-out, under Do Not Track or while the
kill switch is on.
Wire protocol
Every SDK sends the same protocol: POST {endpoint}/ingest/{events|logs|errors|heartbeat} with the X-ACR-Api-Key
header (and X-ACR-Secret-Key for server keys). The credential determines the app. The body is
{ schemaVersion: 1, sdk, items[1..500] }.
Each item has a client id, which lets the server drop duplicates when a batch is retried.
Retries use exponential backoff with jitter for network errors, 429 and 5xx responses. Other 4xx responses are not retried.
Telemetry is buffered in a bounded in-memory queue. When it is full, the oldest items are dropped and counted in stats().
SDK code never throws into the host application.
Metrics (increment, gauge, histogram) and traces are not yet available.
