@proyecta-ai/analytics
v0.1.11
Published
Analytics client for Proyecta applications
Maintainers
Readme
@proyecta-ai/analytics
Client-side analytics for Proyecta applications. Captures pageviews, clicks, custom events, and Web Vitals with automatic session and device tracking.
Installation
npm install @proyecta-ai/analytics
# or
pnpm add @proyecta-ai/analyticsQuick Start
The simplest way to get started is initAnalytics(), which creates a singleton Analytics instance and automatically tracks the initial pageview:
import { initAnalytics } from '@proyecta-ai/analytics';
const analytics = initAnalytics({
appId: 'your-app-id',
apiEndpoint: 'https://cloud.proyecta.dev',
trackPerformance: true,
});This is how the Proyecta webapp template initializes analytics:
// main.tsx
import { initAnalytics } from '@proyecta-ai/analytics';
const appId = import.meta.env.VITE_PROYECTA_APP_ID;
if (appId) {
initAnalytics({
appId,
apiEndpoint: import.meta.env.VITE_PROYECTA_CLOUD_API_URL,
trackPerformance: true,
});
}Configuration
The AnalyticsConfig interface accepts these options:
| Property | Type | Default | Description |
| ------------------ | --------- | -------------- | ------------------------------------------------------------------------------- |
| appId | string | (required) | App/prototype ID used to scope events and authenticate with Proyecta Cloud |
| apiEndpoint | string | '' | Proyecta Cloud base URL (e.g. https://cloud.proyecta.dev) |
| debug | boolean | false | Log events and errors to the console |
| enabled | boolean | !!appId | Master on/off switch |
| bufferSize | number | 10 | Flush the event buffer after this many events |
| flushInterval | number | 5000 | Auto-flush interval in milliseconds |
| trackClicks | boolean | false | Automatically track clicks on links, buttons, and [data-track-click] elements |
| trackPerformance | boolean | true | Collect Web Vitals and navigation timing |
API
initAnalytics(config): Analytics
Creates a singleton Analytics instance and tracks the initial pageview automatically. Subsequent calls return the same instance.
new Analytics(config)
Creates a new Analytics instance without the automatic initial pageview. Use this when you need multiple instances or want full control over when the first pageview fires.
Emitting events from app code
initAnalytics() is called once (in main.tsx). Everywhere else, reach the same singleton through the top-level helpers — no need to thread the initAnalytics return value through props or context:
import { track, identify, analytics } from '@proyecta-ai/analytics';
track('cta-click', { location: 'hero' });
identify('user_123');
// or the namespaced facade — identical behaviour:
analytics.track('form-submit', { form: 'contact' });All of these safely no-op before init and on surfaces where tracking is gated off (builder preview, automation) — they never throw, so no null checks are needed at the call site.
getAnalytics(): Analytics | null
Returns the singleton created by initAnalytics, or null if it hasn't been initialized. Use the top-level track/identify/analytics helpers instead unless you need the instance directly.
analytics.trackPageview(properties?)
Track a pageview. Includes navigation timing metrics (plt, di, ttfb) when trackPerformance is enabled.
analytics.trackPageview();
analytics.trackPageview({ section: 'pricing' });analytics.track(eventName, properties?)
Track a custom event. Properties can be strings, numbers or booleans -- numeric values are stored separately for aggregation, and a boolean is stored as the string "true" / "false".
analytics.track('signup_completed', { plan: 'pro' });
analytics.track('purchase', { amount: 49.99, currency: 'USD' });
analytics.track('cta-click', { location: 'hero', signedIn: true });analytics.identify(userId)
Associate a user ID with the current session.
analytics.identify('user_123');analytics.flush()
Manually flush the event buffer, sending all buffered events to the API endpoint and any registered providers.
analytics.reset()
Clear the event buffer, generate a new session ID, and remove the user ID.
analytics.destroy()
Stop auto-flush, flush remaining events, and tear down the instance.
analytics.addProvider(provider) / analytics.removeProvider(name)
Register or remove a custom AnalyticsProvider for sending events to additional destinations.
import { ConsoleProvider } from '@proyecta-ai/analytics';
analytics.addProvider(new ConsoleProvider());Features
Pageview Tracking
trackPageview() records the current URL, referrer, UTM parameters, and browser/OS info. When trackPerformance is enabled, navigation timing metrics (page load time, DOM interactive, TTFB) are attached.
Click Tracking
When trackClicks: true, clicks on <a>, <button>, and elements with data-track-click are automatically captured with element metadata (tag, text, class, id, href).
Web Vitals
When trackPerformance is enabled, the library observes Core Web Vitals (LCP, CLS, INP, FCP, TTFB) via the web-vitals library and sends a web_vitals event once critical metrics are available.
Session Management
- No cookies, no browser storage. Nothing is written to the visitor's device, so the analytics needs no consent banner.
- Visitor ID: derived on the server (Proyecta Cloud) as a hash of a daily random salt, the app id, the IP address and the user agent. Unique per day; not linkable across days. The IP is not stored.
- Session ID: the browser sends a per-page-load id held in memory; the server replaces it with a session that continues across refreshes and tabs until 30 minutes pass without an event.
- In-site navigation: pageviews after the first in a page load carry the previous page as their referrer, with
referrer_source: 'internal', so they never re-credit the entry source. - Page leave:
pageleaveevents fire onbeforeunloadwithkeepalivefetch for reliable delivery.
Custom Events
track() sends events with event_type: 'custom' and the specified event_name. String and numeric properties are separated for efficient storage and aggregation.
Event Types
All events conform to the ProyectaEvent schema (see schema.ts):
| event_type | Description |
| ------------ | ----------------------------------- |
| pageview | Page load or navigation |
| pageleave | User leaving the page |
| web_vitals | Core Web Vitals measurements |
| click | User click (auto-tracked or manual) |
| custom | Custom events via track() |
Sub-path Exports
import type { ProyectaEvent } from '@proyecta-ai/analytics/schema';
import type { AnalyticsConfig, PerformanceMetrics } from '@proyecta-ai/analytics/types';
import { observeWebVitals, debounce, throttle } from '@proyecta-ai/analytics/utils';