Cookie consent state and consent-gated event tracking for React and TypeScript, with Do Not Track and an SSR consent cookie.
Version-matched docs ship in the package: docs/API.md, llms.txt,
CHANGELOG.md and the TypeScript sources in src/. Read them before writing code.
- Use it when a React app needs cookie-banner state stored in
localStorageand a cookie. - Use it when tracking calls must wait for consent and stop on Do Not Track or a decline.
- Use it when server code must read the visitor's choice from the
Cookieheader. - Do not use it when events must reach a backend: it sends nothing; use your analytics vendor's SDK.
- Do not use it for a server-side consent record: use
@vllnt/convex-consent.
pnpm add @vllnt/analyticsimport { track } from "@vllnt/analytics";
import { AnalyticsProvider, useAnalytics } from "@vllnt/analytics/react";
const config = { app: "my-app" };
function Banner() {
const { hasResponded, acceptAll, declineAnalytics } = useAnalytics();
return hasResponded ? null : <p><button onClick={acceptAll}>Accept</button><button onClick={declineAnalytics}>Decline</button></p>;
}
export const App = () => (
<AnalyticsProvider config={config}><Banner /><button onClick={() => track("cta_click")}>Buy</button></AnalyticsProvider>
);Every public export. Full signatures and examples: docs/API.md.
| Export | Entry | What it does |
|---|---|---|
initAnalytics |
., ./react |
Starts the shared instance and flushes queued events, unless blocked. |
track |
. |
Records a custom event; queued before init, dropped while blocked. |
trackPage |
. |
Records a page view, queued before init like track. |
identify |
. |
Stores a user id and traits on the started instance. |
resetAnalytics |
. |
Clears the user id and traits (logout). |
enableAnalytics |
. |
Unblocks after consent is granted and starts again. |
disableAnalytics |
. |
Blocks tracking and empties the queue. |
isAnalyticsEnabled |
. |
true when started and not blocked. |
getAnalyticsState |
. |
Current instance state, for debugging. |
DEFAULT_MAX_QUEUED_EVENTS |
. |
Default maxQueuedEvents, 100. |
trackTutorialStart |
. |
Tracks a tutorial_start event. |
trackSectionView |
. |
Tracks a tutorial_section_view event. |
trackSectionComplete |
. |
Tracks a tutorial_section_complete event. |
trackTutorialComplete |
. |
Tracks a tutorial_complete event. |
trackTutorialNavigation |
. |
Tracks a tutorial_navigation event. |
trackTimeSpent |
. |
Tracks a tutorial_time_spent event. |
CONSENT_VERSION |
. |
Default consent version, 1. |
CONSENT_STORAGE_KEY |
. |
localStorage key, "vllnt:analytics-consent". |
CONSENT_COOKIE_NAME |
. |
Cookie name, "vllnt-consent". |
loadConsent |
. |
Reads and validates stored consent, or null. |
saveConsent |
. |
Writes consent to localStorage and the cookie. |
clearConsent |
. |
Removes stored consent and expires the cookie. |
createAcceptAllConsent |
. |
New consent state with everything accepted. |
createDeclineAnalyticsConsent |
. |
New consent state with analytics declined. |
updateConsentCategory |
. |
Copy of a consent state with one category changed. |
needsRePrompt |
. |
true when stored consent is older than a version. |
getConsentFromCookie |
. |
Parses the consent cookie from a Cookie header. |
isDoNotTrackEnabled |
. |
true when the browser sends Do Not Track. |
isStorageAvailable |
. |
true when localStorage can be written. |
isValidConsentState |
. |
Type guard for a stored consent object. |
AnalyticsProvider |
./react |
Context provider that wires consent to tracking. |
useAnalytics |
./react |
Provider context: consent state and actions. |
useConsent |
./react |
Standalone consent state; does not start tracking. |
AnalyticsConfig |
. (type) |
{ app; debug?; maxQueuedEvents?; version? }. |
AnalyticsEvent |
. (type) |
A queued event: name, properties, timestamp. |
ConsentCategory |
. (type) |
"analytics" | "functional". |
ConsentState |
. (type) |
Stored consent: categories, timestamp, version. |
TutorialEventName |
. (type) |
Event names used by the tutorial helpers. |
TutorialEventProperties |
. (type) |
Properties for the tutorial helpers. |
UseConsentOptions |
. (type) |
{ consentVersion? }. |
UseConsentReturn |
. (type) |
Return value of useConsent. |
Stored consent is read in the browser only, so on the server hasResponded is false. Render the
banner after mount to avoid a hydration mismatch.
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>
);
}import { getConsentFromCookie } from "@vllnt/analytics";
export function GET(request: Request): Response {
const allowed = getConsentFromCookie(request.headers.get("cookie") ?? "");
return Response.json({ allowed });
}Raise consentVersion. Stored choices with a lower version are cleared once; new choices are saved
with the new version.
import type { ReactNode } from "react";
import { AnalyticsProvider } from "@vllnt/analytics/react";
const config = { app: "my-app" };
export function Root({ children }: { children: ReactNode }) {
return (
<AnalyticsProvider config={config} consentVersion={2}>
{children}
</AnalyticsProvider>
);
}import { useAnalytics } from "@vllnt/analytics/react";
export function PrivacySettings() {
const { consent, updateConsent, resetConsent } = useAnalytics();
return (
<div>
<label>
<input
type="checkbox"
checked={consent?.analytics ?? false}
onChange={(event) => updateConsent("analytics", event.target.checked)}
/>
Analytics
</label>
<button onClick={resetConsent}>Ask me again</button>
</div>
);
}import { identify, resetAnalytics, trackPage, trackSectionView } from "@vllnt/analytics";
trackPage({ path: "/about" });
identify("user-123", { plan: "pro" });
resetAnalytics();
trackSectionView({
tutorial_id: "getting-started",
tutorial_title: "Getting Started",
locale: "en",
section_id: "intro",
section_index: 0,
total_sections: 5,
});import {
createAcceptAllConsent,
createDeclineAnalyticsConsent,
disableAnalytics,
enableAnalytics,
initAnalytics,
loadConsent,
saveConsent,
} from "@vllnt/analytics";
const config = { app: "my-app" };
// A stored accept starts tracking; a stored decline blocks it and drops queued events.
if (loadConsent()) initAnalytics(config);
export function onAccept(): void {
saveConsent(createAcceptAllConsent());
enableAnalytics(config);
initAnalytics(config);
}
export function onDecline(): void {
saveConsent(createDeclineAnalyticsConsent());
disableAnalytics();
}The package has no error codes. These are every message it throws or logs as a warning.
| Message | Kind | Cause | Fix |
|---|---|---|---|
useAnalytics must be used within an AnalyticsProvider |
thrown by useAnalytics() |
The hook ran outside <AnalyticsProvider>. |
Render the component inside <AnalyticsProvider>, or use useConsent(). |
Failed to save consent: |
console.warn from saveConsent() |
The write probe (isStorageAvailable()) succeeded, but writing the consent value to localStorage or setting the cookie threw, for example because the value did not fit in the space left. On a completely full quota the probe fails first, so saveConsent() returns without saving and without this warning. |
The new choice applies on this page but is not stored, so later visits load the earlier stored choice, if any. A failed accept over a stored decline stays blocked on this page too, because initAnalytics re-reads the stored decline. Free storage, or call clearConsent() after a failed save. |
- No transport and no event callback: events never leave the page. With
debug: truethey are logged withconsole.logas[analytics:track],[analytics:page]and similar. - Until
initAnalytics()runs,track()andtrackPage()are queued in memory. The queue keeps the firstmaxQueuedEventscalls (default 100, shared by both) and drops later ones;0queues nothing.AnalyticsProviderappliesconfig.maxQueuedEventson mount. Without the provider, the default applies untilinitAnalytics()runs; it then keeps only the firstmaxQueuedEventsqueued events. The first unblockedinitAnalytics()flushes them; a decline or a Do Not Track block drops them. AfterresetConsent(), tracking is blocked and events are dropped until the visitor responds again. identify()before init or while blocked does nothing; it is not queued.track()with an empty or non-string name andidentify()with an empty or non-string id do nothing.initAnalytics()runs once: later calls, and laterconfigvalues, are ignored while an instance exists. Pass a stableconfig(a module constant) toAnalyticsProvider.- Once blocked, only
enableAnalytics()unblocks. It re-reads stored consent, so save the accepted consent first, and it does nothing while Do Not Track ("1"or"yes") is on. disableAnalytics()keeps the user id and traits; callresetAnalytics()to clear them.- On the server,
track,trackPage,identifyandresetAnalyticsdo nothing andloadConsentreturnsnull.initAnalyticshas no server guard: call it only in the browser. - When
localStoragecannot be written (isStorageAvailable()isfalse, for example blocked or completely full storage),saveConsentandclearConsentdo nothing and log nothing, so a new choice lasts for the current page only.loadConsentstill reads a stored choice wheneverlocalStoragecan be read, so a stored decline keeps tracking blocked, also after an accept that could not be saved. updateConsent("functional", false)is ignored: functional consent is always on.updateConsentdoes nothing whileconsentisnull.useConsent()reads and writes stored consent only; it does not start or stop tracking and does not share state withAnalyticsProvider.isLoadingis alwaysfalse.- The cookie is
vllnt-consent=1orvllnt-consent=0, with a one-year expiry,path=/andSameSite=Lax, and withoutSecureorHttpOnly.
AnalyticsProvider mounts
├─ Stored consent older than consentVersion ──▶ cleared, banner shown again
├─ Analytics accepted ──▶ initAnalytics()
│ ├─ Do Not Track on ──▶ blocked, queue dropped
│ └─ otherwise ──▶ started, queue flushed
├─ Analytics declined ──▶ disableAnalytics(); track() calls dropped
└─ No consent yet ──▶ no init; first maxQueuedEvents track() calls queued in memory
- React: peer range
^18.0.0 || ^19.0.0, used by./reactonly. - TypeScript users need
@types/react18.2.6 or later: the./reactdeclarations useReact.JSX.Element. - Module formats: ESM and CommonJS, with type declarations for both, from
dist/. ./reactstarts with"use client"in both builds; the core entry does not, so server code can import it.- Runtimes: browsers for tracking and consent storage. Server runtimes can import every entry point;
there, use
getConsentFromCookieto read consent.
The analytics state is a module-level singleton with no public reset. In your tests, clear
localStorage between cases and load the module fresh when a case needs a new instance.
This repository's own checks: pnpm lint, pnpm typecheck, pnpm test:coverage (Vitest with
jsdom, 100% coverage gate), pnpm build and pnpm test:package (installs the packed tarball in a
clean project with the repo's release-age rule, and imports and type-checks every entry point).
Report vulnerabilities privately through GitHub Security Advisories. Releases are published from CI with npm trusted publishing and provenance.
None: no other @vllnt package is used together with this one in code.
See CONTRIBUTING.md. Setup:
pnpm install, then pnpm lint && pnpm typecheck && pnpm test:coverage && pnpm build && pnpm test:package.
- Docs and changelog: oss.vllnt.com/packages/analytics · release feed
- All @vllnt packages: oss.vllnt.com · search packages and docs on index.vllnt.com
- Source and issues: GitHub · issues
- Questions and updates: Discord · X @bntvllnt
- Company and author: vllnt.com · bntvllnt.com · GitHub @bntvllnt · LinkedIn
- Sponsor: GitHub Sponsors
Part of vllnt open source · Package page · vllnt.com · Built by bntvllnt