@xorblin.com/ana.js
v1.0.0
Published
A lightweight client-side analytics tracking library supporting HTML, React, and Svelte.
Maintainers
Readme
ana.js
ana.js is a premium, modern, and lightweight (under 10KB) client-side analytics and telemetry engine designed to run seamlessly in Vanilla HTML, React, and Svelte applications. It tracks page views (including Single Page Application route transitions), user sessions, UTM campaign attributions, and advanced canvas-based browser fingerprinting to identify unique visitors securely and anonymously without relying solely on storage identifiers.
Events are queued and dispatched in highly efficient batches using the native browser fetchLater API, which guarantees delivery even as users navigate away or close pages, while minimizing network requests and server load.
Key Features
- Multi-Framework Native ESM/UMD: Distributed as both a modern ES Module (for React/Svelte) and a global UMD package (for standard HTML script tags).
- Transient & Persistent Tracking: Matches a persistent visitor UUID (in
localStorage) with sliding 30-minute session activities (insessionStorage). - Canvas Fingerprinting: Generates stable, privacy-focused browser/device hashes by rendering colored texts, overlapping shapes, and emojis to an offscreen canvas and hashing the output with a rapid 64-bit non-cryptographic hash (
cyrb53). - UTM campaign attribution: Automatically extracts UTM values from the URL on landing pages and caches them in session storage to annotate subsequent pages and custom events.
- SPA Auto-Tracking: Monkey-patches browser History API states (
pushState,replaceState, andpopstate) to record virtual pageviews without routing wrappers. - Auto-Click Telemetry: Captures button clicks, anchor link clicks, and elements with explicit
data-ana-clicktracking tags. - FetchLater Batch Beaconing: Batches telemetries within a configurable window (e.g., 5 seconds) and sends them via the browser-native
fetchLaterAPI. Includes polyfills falling back tokeepalivefetch calls ornavigator.sendBeacon.
Installation & Building
Prerequisites
- Node.js (v18+)
- NPM (v9+)
Installation
Clone or move the project into your workspace and install developer dependencies:
npm installBuild Distribution Targets
Build the ESM module, UMD package, and TypeScript declarations (.d.ts):
npm run buildThe output files will be created in the dist/ directory:
dist/ana.js: ES Moduledist/ana.umd.cjs: UMD moduledist/index.d.ts: Main type declarations
Integration Reference
1. Vanilla HTML Script
<!-- Load the UMD bundle -->
<script src="dist/ana.umd.cjs"></script>
<script>
// Initialize the global Ana tracker instance
Ana.init({
endpoint: 'http://localhost:3000/api/analytics',
autoTrackPageViews: true,
autoTrackClicks: true, // Captures buttons, anchor links, and [data-ana-click] tags
batchWindow: 5000, // Wait 5 seconds to batch events
debug: true // Exposes debug logs in console
});
// Track a custom event
document.getElementById('buy-now').addEventListener('click', () => {
Ana.track('click_checkout', { cart_value: 49.99 });
});
</script>2. React (ES Module)
import React, { useEffect } from 'react';
import { Ana } from 'ana.js';
// Initialize once at the root entry point (e.g., main.jsx or index.js)
Ana.init({
endpoint: 'http://localhost:3000/api/analytics',
autoTrackPageViews: true,
debug: false
});
export default function App() {
const handleFeatureClick = (featureName) => {
Ana.track('feature_click', { feature: featureName });
};
return (
<div>
<button onClick={() => handleFeatureClick('dark_mode')}>Toggle Theme</button>
</div>
);
}3. Svelte (ES Module)
<script>
import { onMount } from 'svelte';
import { Ana } from 'ana.js';
// Initialize once
Ana.init({
endpoint: 'http://localhost:3000/api/analytics',
autoTrackPageViews: true,
autoTrackClicks: true
});
function logNewsletterSignup() {
Ana.track('newsletter_signup', { location: 'footer' });
}
</script>
<button on:click={logNewsletterSignup}>Join Newsletter</button>Configuration API
The Ana.init(config) method takes an AnaConfig object with the following properties:
| Property | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| endpoint | string | Required | The ingest server endpoint URL for events. |
| autoTrackPageViews | boolean | true | Hook SPA route changes and initial page loads. |
| autoTrackClicks | boolean | false | Hook document click events for buttons/links. |
| batchWindow | number | 5000 | Time in ms to batch events. Set to 0 for immediate dispatch. |
| maxQueueSize | number | 100 | Threshold of events before forcing an immediate sync. |
| debug | boolean | false | Enable console warnings and events printouts. |
Running Verification Examples
A mock local telemetry server is provided to easily verify payloads locally.
Start the Mock Ingest Server:
node examples/server.jsThis launches an endpoint at
http://localhost:3000/api/analyticsthat outputs incoming JSON event streams to the console.Open the Demos:
- Vanilla UMD Dashboard: Open
examples/vanilla/index.htmldirectly in a browser. - React Application: Navigate to
examples/react-demo, runnpm install && npm run dev, and visit the browser page. - Svelte Application: Navigate to
examples/svelte-demo, runnpm install && npm run dev, and visit the browser page.
- Vanilla UMD Dashboard: Open
Run Automated Test Assertions:
node tests/integration.test.js
