@sarfarajey/analytics-logger
v1.0.0
Published
GA4 analytics abstraction with debouncing, traffic source detection, and user ID stitching
Maintainers
Readme
@sarfarajey/analytics-logger
GA4 analytics abstraction for browser apps. Configuration-gated dispatch, debouncing for high-frequency events, traffic source detection, and user ID stitching.
Install
npm install @sarfarajey/analytics-loggerSetup
Call configure() once at app bootstrap (e.g. in your layout component or <script> tag):
import { configure } from '@sarfarajey/analytics-logger';
configure({
// Only dispatch on production
isEnabled: () => window.location.hostname === 'example.com',
// Optional second provider (Plausible, PostHog, custom endpoint, etc.)
secondaryDispatch: (name, props) => {
window.plausible?.(name, { props });
},
// Events to debounce (600ms, only last call fires)
debouncedEvents: ['slider_change', 'simulation_run'],
});Usage
import { logEvent, logPageView, setAnalyticsUserId, detectTrafficSource } from '@sarfarajey/analytics-logger';
// Page view (auto-attaches traffic_source)
logPageView({ page: '/dashboard/', title: 'Dashboard' });
// Custom event
logEvent('button_click', { label: 'Export PDF', format: 'A4' });
// Debounced event (configured above) — only last call within 600ms fires
logEvent('slider_change', { value: 42 });
// Stitch an authenticated user to anonymous GA4 events
setAnalyticsUserId('user-abc-123');
// Clear on sign-out
setAnalyticsUserId(null);
// Inspect traffic source directly
const source = detectTrafficSource();
// → 'direct' | 'seo' | 'linkedin' | 'referral:github.com' | 'utm_campaign_value' | 'unknown'API
configure(config)
Configure the logger. Must be called before logEvent.
interface AnalyticsConfig {
isEnabled: () => boolean;
secondaryDispatch?: (name: string, props: EventProps) => void;
debouncedEvents?: string[]; // default: ['simulation_run', 'cost_override', 'calculate_click']
}logEvent(name, props?)
Dispatch an event. Debounced events are coalesced over 600ms.
logPageView(props?)
Shorthand for logEvent('page_view', { traffic_source, ...props }).
setAnalyticsUserId(uid)
Set or clear GA4 user_id for anonymous → registered stitching.
detectTrafficSource()
Returns the current traffic source as a string: 'direct', 'seo', 'linkedin', 'internal', 'referral:<host>', UTM source value, or 'unknown'.
License
MIT
