Reference for every public export of this package version, written from src/index.ts and
src/react.tsx. Those sources ship in this package under src/. Errors and their fixes are in the
README: Errors and fixes.
The library has no transport. Events are queued and gated by consent, then dropped; with
debug: true they are written to console.log. Send them to your own backend yourself.
Only these subpaths are exported (package.json exports). Each has ESM, CommonJS and type
declarations in dist/.
| Import | Contents |
|---|---|
@vllnt/analytics |
Tracking functions, consent functions and constants, types |
@vllnt/analytics/react |
AnalyticsProvider, useAnalytics, useConsent, initAnalytics |
@vllnt/analytics/package.json |
Package metadata |
Types are exported from @vllnt/analytics only. Within one module format, both entry points share
one analytics state, so initAnalytics from ./react and track from . act on the same instance.
The ESM and CommonJS builds each have their own copy, so mixing import and require in one
process gives two instances.
Peer dependency: react ^18.0.0 || ^19.0.0 (used by ./react only). TypeScript users need
@types/react 18.2.6 or later: the ./react declarations use React.JSX.Element.
All browser APIs are guarded, so importing on the server is safe. On the server track,
trackPage, identify and resetAnalytics return early, loadConsent returns null, and
isStorageAvailable and isDoNotTrackEnabled return false. getConsentFromCookie only parses
the string it is given, so it is the consent reader to use on the server. initAnalytics,
enableAnalytics and disableAnalytics have no server guard: initAnalytics on the server
starts the process-wide instance, so call it only in the browser.
Signature: initAnalytics(config: AnalyticsConfig): void
Starts the shared analytics instance and flushes queued events. Later calls do nothing while an
instance exists. It does not start, and blocks tracking, when Do Not Track is on ("1" or
"yes") or stored consent has analytics: false; already queued events are then dropped, so
they are never flushed later. With no stored consent it starts, so call it only after the user
accepts if you need opt-in (AnalyticsProvider does this for you). Once tracking is blocked (by a
blocked init or by disableAnalytics), calling initAnalytics again does not unblock it; only
enableAnalytics does. It applies config.maxQueuedEvents first, so only the first
maxQueuedEvents queued events are kept.
import { initAnalytics } from "@vllnt/analytics";
initAnalytics({ app: "my-app", version: 1, debug: true });Signature: track(name: string, properties?: Record<string, unknown>): void
Records a custom event. Before initAnalytics the event is queued; while blocked it is dropped.
An empty or non-string name is ignored. The queue keeps the first maxQueuedEvents calls to
track and trackPage together (default DEFAULT_MAX_QUEUED_EVENTS, 100) and drops later
calls. Events after init are not limited.
import { track } from "@vllnt/analytics";
track("button_click", { id: "cta-hero" });Signature: trackPage(properties?: Record<string, unknown>): void
Records a page view, queued before init like track. Page views and custom events share one
queue limit.
import { trackPage } from "@vllnt/analytics";
trackPage({ path: "/about" });Signature: identify(userId: string, traits?: Record<string, unknown>): void
Stores a user id and traits on the started instance. Ignored before init, while blocked, or
when userId is empty or not a string. Not queued.
import { identify } from "@vllnt/analytics";
identify("user-123", { plan: "pro" });Signature: resetAnalytics(): void
Clears the stored user id and traits (for logout). The instance stays started.
import { resetAnalytics } from "@vllnt/analytics";
resetAnalytics();Signature: enableAnalytics(config: AnalyticsConfig): void
Unblocks, discards the current instance and runs initAnalytics(config) again. Does nothing
unless tracking is currently blocked, and does nothing while Do Not Track is on. Because it
re-reads stored consent, save the accepted consent first: a stored analytics: false blocks it
again. The new instance has no userId or traits.
import { createAcceptAllConsent, enableAnalytics, saveConsent } from "@vllnt/analytics";
saveConsent(createAcceptAllConsent());
enableAnalytics({ app: "my-app" });Signature: disableAnalytics(): void
Blocks tracking and empties the queue after consent is revoked. It keeps the in-memory user id
and traits; call resetAnalytics() or reload the page to clear them.
import { disableAnalytics, resetAnalytics } from "@vllnt/analytics";
disableAnalytics();
resetAnalytics();Signature: isAnalyticsEnabled(): boolean
true when the instance has started and is not blocked.
import { isAnalyticsEnabled, track } from "@vllnt/analytics";
if (isAnalyticsEnabled()) track("export_clicked");Signature: getAnalyticsState(): { app: string; debug?: boolean; version?: number; userId?: string; traits?: Record<string, unknown> } | undefined
Returns the current instance state for debugging, or undefined before init. The state type is
not exported.
import { getAnalyticsState } from "@vllnt/analytics";
console.log(getAnalyticsState()?.userId);Value: 100
The default for AnalyticsConfig.maxQueuedEvents: how many track and trackPage calls are
queued before init. A maxQueuedEvents that is not a non-negative safe integer (for example
-1, 1.5 or NaN) means this default. 0 queues nothing. AnalyticsProvider applies
config.maxQueuedEvents on mount, before initAnalytics runs. Without the provider, the default
applies until initAnalytics(config) runs.
import { DEFAULT_MAX_QUEUED_EVENTS, initAnalytics } from "@vllnt/analytics";
initAnalytics({ app: "my-app", maxQueuedEvents: DEFAULT_MAX_QUEUED_EVENTS * 2 });Typed wrappers around track with fixed event names (TutorialEventName). Every helper
needs tutorial_id, tutorial_title and locale.
| Function | Event name | Extra required fields |
|---|---|---|
trackTutorialStart(properties) |
tutorial_start |
none (section_id not allowed) |
trackSectionView(properties) |
tutorial_section_view |
none |
trackSectionComplete(properties) |
tutorial_section_complete |
none |
trackTutorialComplete(properties) |
tutorial_complete |
none (section_id not allowed) |
trackTutorialNavigation(properties) |
tutorial_navigation |
navigation_type |
trackTimeSpent(properties) |
tutorial_time_spent |
time_spent_seconds |
import { trackSectionView, trackTutorialNavigation } from "@vllnt/analytics";
const base = { tutorial_id: "intro", tutorial_title: "Intro", locale: "en" };
trackSectionView({ ...base, section_id: "setup", section_index: 0, total_sections: 5 });
trackTutorialNavigation({ ...base, section_id: "setup", navigation_type: "next" });Consent is stored as JSON in localStorage under CONSENT_STORAGE_KEY and mirrored to the
CONSENT_COOKIE_NAME cookie (1 allowed, 0 declined; one-year expiry, path=/,
SameSite=Lax) so the server can read it.
| Name | Value |
|---|---|
CONSENT_VERSION |
1 |
CONSENT_STORAGE_KEY |
"vllnt:analytics-consent" |
CONSENT_COOKIE_NAME |
"vllnt-consent" |
Signature: loadConsent(): ConsentState | null
Reads and validates stored consent. null when none is stored, the value is invalid, there is no
window, or reading localStorage throws. It reads without a write probe, so a stored choice is
found even when the storage quota is full.
import { loadConsent } from "@vllnt/analytics";
const consent = loadConsent();
console.log(consent?.analytics);Signature: saveConsent(state: ConsentState): void
Writes consent to localStorage and the cookie. Does nothing, without a warning, when
isStorageAvailable() is false, which includes a completely full quota. Logs
Failed to save consent: with console.warn when that probe succeeds but writing the consent
value or the cookie throws.
import { createAcceptAllConsent, saveConsent } from "@vllnt/analytics";
saveConsent(createAcceptAllConsent());Signature: clearConsent(): void
Removes stored consent and expires the cookie.
import { clearConsent } from "@vllnt/analytics";
clearConsent();Signature: createAcceptAllConsent(): ConsentState
New state with analytics: true, functional: true, the current time and CONSENT_VERSION. To
record another version, override it: { ...createAcceptAllConsent(), version: 2 }.
import { createAcceptAllConsent } from "@vllnt/analytics";
const accepted = createAcceptAllConsent();
console.log(accepted.version);Signature: createDeclineAnalyticsConsent(): ConsentState
New state with analytics: false, functional: true, the current time and CONSENT_VERSION.
import { createDeclineAnalyticsConsent } from "@vllnt/analytics";
const declined = createDeclineAnalyticsConsent();
console.log(declined.analytics);Signature: updateConsentCategory(current: ConsentState, category: ConsentCategory, value: boolean): ConsentState
Returns a copy with one category changed and a new timestamp. Setting functional to false
returns current unchanged.
import { loadConsent, saveConsent, updateConsentCategory } from "@vllnt/analytics";
const stored = loadConsent();
if (stored) saveConsent(updateConsentCategory(stored, "analytics", false));Signature: needsRePrompt(consent: ConsentState, currentVersion: number): boolean
true when consent.version < currentVersion.
import { clearConsent, loadConsent, needsRePrompt } from "@vllnt/analytics";
const consent = loadConsent();
if (consent && needsRePrompt(consent, 2)) clearConsent();Signature: getConsentFromCookie(cookieString: string): boolean | null
Parses a Cookie header: true for 1, false for any other value, null when the cookie is
absent or empty (vllnt-consent=). The name must start the string or follow ;, so
evil-vllnt-consent=1 does not match.
import { getConsentFromCookie } from "@vllnt/analytics";
export function isAllowed(request: Request): boolean | null {
return getConsentFromCookie(request.headers.get("cookie") ?? "");
}Signature: isDoNotTrackEnabled(): boolean
Reads navigator.doNotTrack, then window.doNotTrack, then navigator.msDoNotTrack, and
returns true when the first one that is set equals "1" or "yes". false on the server.
import { isDoNotTrackEnabled } from "@vllnt/analytics";
const showBanner = !isDoNotTrackEnabled();
console.log(showBanner);Signature: isStorageAvailable(): boolean
true when a test key can be written to and removed from localStorage. false on the server
or when that probe throws, for example when storage is blocked or the quota is full. loadConsent
does not depend on it, so a stored choice can still be read when it is false.
import { isStorageAvailable } from "@vllnt/analytics";
if (!isStorageAvailable()) console.warn("consent will not persist");Signature: isValidConsentState(value: unknown): value is ConsentState
Type guard: checks the four fields and their types.
import { isValidConsentState, saveConsent } from "@vllnt/analytics";
const parsed: unknown = JSON.parse('{"analytics":true,"functional":true,"timestamp":"2026-01-01T00:00:00.000Z","version":1}');
if (isValidConsentState(parsed)) saveConsent(parsed);Both builds of this entry (dist/react.js and dist/react.cjs) start with "use client"; the
core entry does not.
Both AnalyticsProvider and useConsent read stored consent during the first render. On the
server that read returns null, so consent is null and hasResponded is false there, while
the first browser render may already see stored consent. If you render a banner from
hasResponded, render it only after the component has mounted to avoid a hydration mismatch.
Signature: AnalyticsProvider(props: { children: ReactNode; config: AnalyticsConfig; consentVersion?: number }): React.JSX.Element
consentVersion defaults to CONSENT_VERSION. The provider reads stored consent, clears it when
needsRePrompt(stored, consentVersion), calls initAnalytics(config) while consent has
analytics: true, and calls disableAnalytics() while it has analytics: false, so after a
stored decline track() calls are dropped, not queued. acceptAll and declineAnalytics save
consent with consentVersion; updateConsent copies the current consent, so it keeps the stored
version. The actions call enableAnalytics or disableAnalytics. Before the user responds (no
stored consent), events are queued in memory and flushed if the user accepts; the provider applies
config.maxQueuedEvents during its first render, so the queue keeps the first maxQueuedEvents
events (default 100), including events from child effects on mount. After
resetConsent(), tracking is blocked and events are dropped until the user responds again. Pass a stable
config (for example a module constant), because the init effect depends on it.
import type { ReactNode } from "react";
import { AnalyticsProvider } from "@vllnt/analytics/react";
const config = { app: "my-app", version: 1 };
export function Root({ children }: { children: ReactNode }) {
return <AnalyticsProvider config={config}>{children}</AnalyticsProvider>;
}Signature: useAnalytics(): UseConsentReturn & { config: AnalyticsConfig }
Returns the provider context; throws useAnalytics must be used within an AnalyticsProvider
outside one. Fields: config, consent, hasResponded, isLoading (always false),
acceptAll(), declineAnalytics(), updateConsent(category, value), resetConsent().
updateConsent does nothing while consent is null (before the user has responded).
import { useEffect, useState } from "react";
import { useAnalytics } from "@vllnt/analytics/react";
export function CookieBanner() {
const { hasResponded, acceptAll, declineAnalytics } = useAnalytics();
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted || hasResponded) return null;
return (
<div>
<button onClick={acceptAll}>Accept</button>
<button onClick={declineAnalytics}>Decline</button>
</div>
);
}Signature: useConsent(options?: UseConsentOptions): UseConsentReturn
Standalone consent state with the same fields as useAnalytics() except config. It reads and
writes stored consent only: it does not start or stop analytics and does not share state with
AnalyticsProvider. Inside a provider, use useAnalytics() for a banner so accepting starts
tracking.
import { useConsent } from "@vllnt/analytics/react";
export function ConsentStatus() {
const { consent, updateConsent } = useConsent({ consentVersion: 1 });
return (
<button onClick={() => updateConsent("analytics", !consent?.analytics)}>
Analytics: {consent?.analytics ? "on" : "off"}
</button>
);
}Re-export of the core initAnalytics, for apps that only import from ./react.
In AnalyticsProvider and useConsent, acceptAll and declineAnalytics save the choice with
consentVersion. updateConsent copies the current consent, so it keeps the stored version. Raising
consentVersion asks every visitor once more; the new choice is then kept on later visits.
Exported from @vllnt/analytics as types only.
type AnalyticsConfig = {
app: string;
debug?: boolean;
maxQueuedEvents?: number; // events queued before init; default 100, 0 queues nothing
version?: number;
};
type AnalyticsEvent = {
name: string;
properties?: Record<string, unknown>;
timestamp?: string;
};
type ConsentCategory = "analytics" | "functional";
type ConsentState = {
analytics: boolean;
functional: boolean;
timestamp: string; // ISO time of the choice
version: number;
};
type TutorialEventName =
| "tutorial_complete"
| "tutorial_navigation"
| "tutorial_section_complete"
| "tutorial_section_view"
| "tutorial_start"
| "tutorial_time_spent";
type TutorialEventProperties = {
tutorial_id: string;
tutorial_title: string;
locale: string;
completion_percent?: number; // 0-100
navigation_type?: "keyboard" | "next" | "prev" | "toc";
section_id?: string;
section_index?: number; // 0-based
time_spent_seconds?: number;
total_sections?: number;
};
type UseConsentOptions = { consentVersion?: number };
type UseConsentReturn = {
acceptAll: () => void;
consent: ConsentState | null;
declineAnalytics: () => void;
hasResponded: boolean;
isLoading: boolean;
resetConsent: () => void;
updateConsent: (category: ConsentCategory, value: boolean) => void;
};