@launchfury/analytics
v0.2.0
Published
Tiny dependency-free browser analytics SDK for LaunchFury first-party analytics.
Maintainers
Readme
@launchfury/analytics
Tiny, dependency-free browser analytics SDK for LaunchFury first-party analytics. Send web and product events to your LaunchFury ingest endpoint. Framework independent, ESM + CJS, fully typed.
Install
pnpm add @launchfury/analyticsQuick start
import { analytics } from "@launchfury/analytics";
analytics.init({
writeKey: "lf_write_key_...",
host: "https://launchfury.com",
});
analytics.capture("signup_started", { plan: "pro" });Auto pageviews fire on init and on SPA navigation (history pushState/replaceState/popstate). Nothing else is required.
Multiple instances
The default export is a shared singleton. Use the factory for isolated instances:
import { createAnalytics } from "@launchfury/analytics";
const a = createAnalytics({ writeKey: "...", host: "https://launchfury.com" });API
| Method | Description |
| --- | --- |
| init(config) | Configure and start the SDK. |
| capture(event, properties?) | Record a custom event. |
| identify(identityToken, properties?) | Associate events with a backend-authenticated user using a signed LaunchFury token. |
| page(properties?) | Record a pageview manually. |
| reset() | Clear identity, queued events, and session state and regenerate the anonymous id. Call on logout. |
| optIn() | Grant consent and start sending. |
| optOut() | Deny consent, stop sending, and clear the queue. Persists across reloads. |
| hasOptedOut() | Whether the visitor has opted out. |
Config
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| writeKey | string | required | Ingest write key. Sent as a bearer token. |
| host | string | required | Ingest base URL, e.g. https://launchfury.com. |
| environment | string | undefined | Optional environment label. |
| autocapturePageviews | boolean | true | Capture pageviews on init and SPA navigation. |
| flushIntervalMs | number | 5000 | Interval between automatic flushes. |
| maxQueueSize | number | 100 | Max queued events; oldest dropped past this. |
| maxBatchSize | number | 50 | Max events per request; a full batch flushes immediately. |
| sessionTimeoutMs | number | 1800000 | Inactivity before a new session begins. |
| requireConsent | boolean | false | If true, nothing sends until optIn(). |
| debug | boolean | false | Log outgoing batches and errors via console.debug. |
Delivery
- Events queue and batch, flushing on interval or when a batch fills.
- Page hide and tab-hidden flush via
navigator.sendBeacon(fetch keepalive fallback). - The queue persists to
localStorageand retries on the next load. - Transient network failures retry with bounded exponential backoff, then drop.
Identifiers
- Anonymous id persists in
localStorage(lf_anon_id). - Session id persists with a last-activity timestamp; a new session starts after
sessionTimeoutMsof inactivity. - UTM parameters (
utm_source/medium/campaign/term/content) are captured once per session on pageviews.
Authenticated users
Create both a browser write key and a server write key. Keep the server key in backend environment configuration. Your product backend remains responsible for authenticating the user.
After login and whenever your app restores a logged-in session, exchange the authenticated app user id from your backend:
const response = await fetch("https://launchfury.com/api/analytics/identity", {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${process.env.LAUNCHFURY_ANALYTICS_SERVER_KEY}`,
},
body: JSON.stringify({ user_id: authenticatedUser.id }),
});
if (response.status === 410) return null;
if (!response.ok) throw new Error("Failed to connect analytics identity");
const { token } = (await response.json()) as { token: string; expires_at: string };Return only token to your browser and connect it:
if (analyticsIdentityToken) analytics.identify(analyticsIdentityToken);Tokens expire after 24 hours and are scoped to one app and environment. Refresh the token during session restoration. Never send the server key or raw app user id to the browser. Never add either value to analytics properties.
Call analytics.reset() on logout. When an authenticated user deletes their account or analytics identity, call the deletion endpoint from your backend with the same server key:
await fetch("https://launchfury.com/api/analytics/identity/delete", {
method: "DELETE",
headers: {
"content-type": "application/json",
authorization: `Bearer ${process.env.LAUNCHFURY_ANALYTICS_SERVER_KEY}`,
},
body: JSON.stringify({ user_id: authenticatedUser.id }),
});Deletion irreversibly removes the link between the app user id and LaunchFury's random analytics person id and prevents that app user id from reconnecting. Existing aggregate event rows remain pseudonymous until the analytics store's fixed retention expires.
Upgrading from 0.1
identify() now accepts only a backend-issued identity token. Raw user_id values are ignored. Ship the server-side identity exchange in the same release as the SDK upgrade; authenticated user counts remain anonymous until the exchange calls identify().
Privacy
The SDK never auto-captures input values, form contents, raw app user ids, or other PII. It sends only structural signals, the signed identity token, and properties you pass. You own consent and privacy: gate init or optIn behind your consent flow and use requireConsent when explicit opt-in is required.
License
MIT
