@proyecta-ai/analytics
v0.1.4
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 |
| cookieDomain | string | '' | Domain for the visitor cookie |
| cookiePath | string | '/' | Path for the visitor cookie |
| sessionTimeout | number | 30 | Session inactivity timeout in minutes |
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.
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 or numbers -- numeric values are stored separately for aggregation.
analytics.track('signup_completed', { plan: 'pro' });
analytics.track('purchase', { amount: 49.99, currency: 'USD' });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
- Visitor ID: Persistent cookie (
_pry_vid, 2-year expiry) identifies returning visitors. - Session ID:
sessionStorage-based with configurable inactivity timeout (default 30 minutes). - 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';