A modern, type-safe analytics library for tracking user events across multiple providers, built by LobeHub
npm install @lobehub/analytics

A modern, type-safe analytics library for tracking user events across multiple providers, built by LobeHub
[![][npm-release-shield]][npm-release-link]
[![][github-releasedate-shield]][github-releasedate-link]
[![][github-action-test-shield]][github-action-test-link]
[![][github-action-release-shield]][github-action-release-link]
[![][github-contributors-shield]][github-contributors-link]
[![][github-forks-shield]][github-forks-link]
[![][github-stars-shield]][github-stars-link]
[![][github-issues-shield]][github-issues-link]
[![][github-license-shield]][github-license-link]
Changelog ยท [Report Bug][github-issues-link] ยท [Request Feature][github-issues-link]

Table of contents
#### TOC
- โจ Features
- ๐ฆ Installation
- โ ๏ธ Client-side vs Server-side Usage
- ๐ Client-side Usage (Browser Environment)
- ๐ฅ๏ธ Server-side Usage (Node.js Environment)
- Import Structure
- ๐ Quick Start
- Basic Usage
- Global Instance Management
- React Integration
- SPM (Source Page Medium) Auto-Prefixing
- ๐ API Reference
- Core Functions
- Global Instance Management
- React Hooks & Provider
- Types
- ๐ ๏ธ Development
- Project Structure
- Examples
- ๐ค Contributing
####
- ๐ฏ Type-safe - Full TypeScript support with predefined events
- ๐ Multi-provider - Built-in PostHog support, extensible for other providers
- ๐ Global Instance Management - Singleton pattern and named global instances
- ๐ SPM Auto-Prefixing - Automatic Source Page Medium tracking with business prefixes
- โ๏ธ React integration - Enhanced Provider with auto-registration and hooks
- ๐๏ธ Easy configuration - Simple setup with business context
- ๐ชถ Lightweight - Minimal dependencies and optimized bundle size
- ๐ง Developer-friendly - Comprehensive error handling and debugging
- ๐งช Test-friendly - Built-in reset and cleanup functions
To install @lobehub/analytics, run the following command:
``bash
npm install @lobehub/analytics
This library includes PostHog analytics provider out of the box. For React integration:
`bash
npm install react # if not already installed
`โ ๏ธ Client-side vs Server-side Usage
$3
`typescript
import { createAnalytics } from '@lobehub/analytics';const analytics = createAnalytics({
business: 'my-app',
providers: {
posthog: { enabled: true, key: 'client_key' },
},
});
`$3
`typescript
import { createServerAnalytics } from '@lobehub/analytics/server';const analytics = createServerAnalytics({
business: 'my-app',
providers: {
// โ
Client-side PostHog (browser compatible)
posthog: {
enabled: true,
key: 'phc_xxxxx',
api_host: 'https://app.posthog.com',
},
// โ
Server-side PostHog (Node.js only)
posthogNode: {
enabled: true,
key: 'server_key',
host: 'https://app.posthog.com',
},
},
});
`> ๐ฅ Separation Solution: Clear entry point separation ensures
posthogNode is completely excluded from client-side builds!Import Structure
The library provides separate entry points for client-side, server-side, and React integration:
`typescript
// Client-side analytics (browser safe)
import { AnalyticsManager, createAnalytics } from '@lobehub/analytics';
// Global instance management
import {
createSingletonAnalytics,
getGlobalAnalytics,
getSingletonAnalytics,
} from '@lobehub/analytics';
// React hooks (separate import)
import {
AnalyticsProvider,
useAnalytics,
useAnalyticsStrict,
useEventTracking,
} from '@lobehub/analytics/react';
// Server-side analytics (includes posthog-node)
import { PostHogNodeAnalyticsProvider, createServerAnalytics } from '@lobehub/analytics/server';
`[![][back-to-top]](#readme-top)
๐ Quick Start
$3
`typescript
import { createAnalytics } from '@lobehub/analytics';// Configure analytics with business context
const analytics = createAnalytics({
business: 'my-app', // Required: business name for SPM prefixing
debug: process.env.NODE_ENV === 'development',
providers: {
posthog: {
enabled: !!process.env.POSTHOG_KEY,
key: process.env.POSTHOG_KEY!,
host: process.env.POSTHOG_HOST, // optional
},
},
});
// Initialize
await analytics.initialize();
// Track events with automatic SPM prefixing
await analytics.trackEvent('user_signup', {
method: 'email',
source: 'landing_page',
spm: 'homepage.cta', // Will become: 'my-app.homepage.cta'
});
// Identify users
await analytics.identify('user_123', {
email: 'user@example.com',
plan: 'pro',
});
`$3
Singleton Pattern (Recommended for simple apps):
`typescript
import { createSingletonAnalytics, getSingletonAnalytics } from '@lobehub/analytics';// Create singleton (usually in app initialization)
const analytics = createSingletonAnalytics({
business: 'my-app',
providers: {
posthog: {
enabled: true,
key: process.env.POSTHOG_KEY!,
},
},
});
await analytics.initialize();
// Access from anywhere in your application
export function trackUserAction() {
const analytics = getSingletonAnalytics();
analytics.trackEvent('button_click', {
button_name: 'signup',
page: 'home',
});
}
`Named Global Instances (For complex apps):
`typescript
import { getGlobalAnalytics, setGlobalAnalytics } from '@lobehub/analytics';// Register multiple instances
setGlobalAnalytics(mainAnalytics, 'main');
setGlobalAnalytics(adminAnalytics, 'admin');
// Use specific instances
getGlobalAnalytics('main').trackEvent('user_action', {});
getGlobalAnalytics('admin').trackEvent('admin_action', {});
`$3
Enhanced AnalyticsProvider with auto-registration:
`typescript
import React from 'react';
import { createAnalytics } from '@lobehub/analytics';
import {
AnalyticsProvider,
useAnalytics,
useAnalyticsStrict
} from '@lobehub/analytics/react';// Create analytics instance
const analytics = createAnalytics({
business: 'my-app',
providers: {
posthog: {
enabled: true,
key: process.env.REACT_APP_POSTHOG_KEY!,
},
},
});
// Provider with auto-registration
function App() {
return (
client={analytics}
autoInitialize={true} // Auto-initialize on mount
registerGlobal={true} // Auto-register as global instance
globalName="main" // Optional: custom global name
>
);
}
// Use in components
function MyComponent() {
const { analytics, isReady, isInitializing, error } = useAnalytics();
// Safe usage with state checking
if (isInitializing) return
Loading analytics...;
if (error) return Analytics error: {error.message};
if (!isReady) return Analytics not ready; const handleClick = () => {
analytics?.trackEvent('button_click', {
button_name: 'cta',
page: 'home',
});
};
return ;
}
// Strict mode (throws if not initialized)
function StrictComponent() {
const analytics = useAnalyticsStrict(); // Throws if not ready
const handleClick = () => {
analytics.trackEvent('button_click', { button_name: 'strict-button' });
};
return ;
}
`Access analytics outside React components:
`typescript
import { getGlobalAnalytics } from '@lobehub/analytics/react';// In service functions, API handlers, etc.
export async function apiCall() {
try {
const response = await fetch('/api/data');
// Track success
const analytics = getGlobalAnalytics('main');
analytics.trackEvent('api_call', {
endpoint: '/api/data',
success: true,
});
return response.json();
} catch (error) {
// Track error
const analytics = getGlobalAnalytics('main');
analytics.trackEvent('api_call', {
endpoint: '/api/data',
success: false,
error: error.message,
});
throw error;
}
}
`$3
The library automatically handles SPM prefixing with your business name:
`typescript
const analytics = createAnalytics({
business: 'my-app', // This will prefix all SPM values
// ... other config
});// These events will have SPM auto-prefixed:
analytics.trackEvent('button_click', {
button_name: 'signup',
spm: 'homepage.hero', // Becomes: 'my-app.homepage.hero'
});
analytics.trackEvent('page_view', {
page: '/dashboard',
spm: 'dashboard.main', // Becomes: 'my-app.dashboard.main'
});
// If no SPM provided, uses business name as default
analytics.trackEvent('user_login', {
method: 'email',
// spm will be: 'my-app'
});
`[![][back-to-top]](#readme-top)
๐ API Reference
$3
####
createAnalytics(config: AnalyticsConfig): AnalyticsManagerCreates a configured analytics manager.
####
AnalyticsManagerMain class for managing analytics providers.
Methods:
-
initialize(): Promise - Initialize all providers
- track(event: AnalyticsEvent): Promise - Track custom event
- trackEvent - Track predefined event
- identify(userId: string, properties?): Promise - Identify user
- trackPageView(page: string, properties?): Promise - Track page view
- reset(): Promise - Reset user identity
- setGlobalContext(context: EventContext): this - Set global context
- getStatus(): { initialized: boolean; providersCount: number } - Get status$3
#### Singleton Pattern
`typescript
// Create singleton
createSingletonAnalytics(config: AnalyticsConfig): AnalyticsManager// Get singleton
getSingletonAnalytics(): AnalyticsManager
getSingletonAnalyticsOptional(): AnalyticsManager | null
// Check singleton
hasSingletonAnalytics(): boolean
resetSingletonAnalytics(): void // For testing
`#### Named Global Instances
`typescript
// Register/unregister
setGlobalAnalytics(instance: AnalyticsManager, name?: string): void
removeGlobalAnalytics(name?: string): boolean
clearGlobalAnalytics(): void// Access
getGlobalAnalytics(name?: string): AnalyticsManager
getGlobalAnalyticsOptional(name?: string): AnalyticsManager | null
// Utilities
hasGlobalAnalytics(name?: string): boolean
getGlobalAnalyticsNames(): string[]
`$3
####
AnalyticsProvider`typescript
client={AnalyticsManager}
autoInitialize?: boolean // Default: true
registerGlobal?: boolean // Default: true
globalName?: string // Default: '__default__'
>
{children}
`#### React Hooks
`typescript
// Safe access with state
useAnalytics(): {
analytics: AnalyticsManager | null;
isReady: boolean;
isInitialized: boolean;
isInitializing: boolean;
error: Error | null;
}// Strict access (throws if not ready)
useAnalyticsStrict(): AnalyticsManager
// State only
useAnalyticsState(): {
isReady: boolean;
isInitialized: boolean;
isInitializing: boolean;
error: Error | null;
}
// Optional access
useAnalyticsOptional(): AnalyticsManager | null
// Legacy hook (for backward compatibility)
useEventTracking(manager: AnalyticsManager): {
trackButtonClick: (buttonName: string, properties?: any) => void;
// ... other convenience methods
}
`$3
####
AnalyticsConfig`typescript
interface AnalyticsConfig {
business: string; // Required: business name for SPM prefixing
debug?: boolean;
providers: {
posthog?: PostHogProviderAnalyticsConfig;
umami?: UmamiProviderAnalyticsConfig;
ga?: GoogleProviderAnalyticsConfig;
};
}
`####
PostHogProviderAnalyticsConfig`typescript
interface PostHogProviderAnalyticsConfig {
enabled: boolean;
key: string;
host?: string;
debug?: boolean;
// ... other PostHog config options
}
`####
PredefinedEvents`typescript
interface PredefinedEvents {
// UI interactions
button_click: {
button_name: string;
page?: string;
section?: string;
spm?: string;
[key: string]: any;
}; // User actions
user_signup: {
method: 'email' | 'oauth' | 'phone';
source?: string;
spm?: string;
[key: string]: any;
};
user_login: {
method: 'email' | 'oauth' | 'phone';
spm?: string;
[key: string]: any;
};
// Chat interactions
chat_message_sent: {
message_length: number;
model?: string;
conversation_id?: string;
spm?: string;
[key: string]: any;
};
// Page tracking
page_view: {
page: string;
referrer?: string;
spm?: string;
[key: string]: any;
};
// Form interactions
form_submit: {
form_name: string;
success: boolean;
spm?: string;
[key: string]: any;
};
}
`[![][back-to-top]](#readme-top)
๐ ๏ธ Development
`bash
Clone the repository
git clone https://github.com/lobehub/@lobehub/analytics.git
cd @lobehub/analyticsInstall dependencies
npm installStart development
npm run devBuild the library
npm run buildRun tests
npm testRun examples
npm run example
`$3
`
@lobehub/analytics/
โโโ src/
โ โโโ base.ts # Base analytics provider
โ โโโ manager.ts # Analytics manager
โ โโโ config.ts # Configuration factory
โ โโโ global.ts # Global instance management
โ โโโ types.ts # TypeScript definitions
โ โโโ providers/ # Analytics providers
โ โ โโโ posthog.ts # PostHog implementation
โ โโโ react/ # React integration
โ โ โโโ provider.tsx # Enhanced Provider component
โ โ โโโ hooks.ts # Legacy hooks
โ โโโ index.ts # Main exports
โโโ examples/ # Usage examples
โโโ dist/ # Built files (generated)
`[![][back-to-top]](#readme-top)
Examples
See the
examples/ directory for comprehensive usage examples:-
examples/library-usage.ts - Basic library usage and design principles
- examples/enhanced-react-usage.tsx - Advanced React integration
- examples/singleton-enhanced-usage.ts - Singleton pattern examples
- examples/global-usage.ts - Global instance management
- examples/business-spm-example.ts - SPM prefixing demonstration
- examples/usage-summary.md` - Complete feature overviewContributions of all types are more than welcome, if you are interested in contributing code, feel free to check out our GitHub [Issues][github-issues-link] to get stuck in to show us what you're made of.
[![][pr-welcome-shield]][pr-welcome-link]
[![][github-contrib-shield]][github-contrib-link]
[![][back-to-top]](#readme-top)
---
#### ๐ License
Copyright ยฉ 2025 [LobeHub][profile-link].
This project is MIT licensed.
[back-to-top]: https://img.shields.io/badge/-BACK_TO_TOP-black?style=flat-square
[github-action-release-link]: https://github.com/lobehub/lobe-analytics/actions/workflows/release.yml
[github-action-release-shield]: https://img.shields.io/github/actions/workflow/status/lobehub/lobe-analytics/release.yml?label=release&labelColor=black&logo=githubactions&logoColor=white&style=flat-square
[github-action-test-link]: https://github.com/lobehub/lobe-analytics/actions/workflows/test.yml
[github-action-test-shield]: https://img.shields.io/github/actions/workflow/status/lobehub/lobe-analytics/test.yml?label=test&labelColor=black&logo=githubactions&logoColor=white&style=flat-square
[github-contrib-link]: https://github.com/lobehub/lobe-analytics/graphs/contributors
[github-contrib-shield]: https://contrib.rocks/image?repo=lobehub%2Flobe-analytics
[github-contributors-link]: https://github.com/lobehub/lobe-analytics/graphs/contributors
[github-contributors-shield]: https://img.shields.io/github/contributors/lobehub/lobe-analytics?color=c4f042&labelColor=black&style=flat-square
[github-forks-link]: https://github.com/lobehub/lobe-analytics/network/members
[github-forks-shield]: https://img.shields.io/github/forks/lobehub/lobe-analytics?color=8ae8ff&labelColor=black&style=flat-square
[github-issues-link]: https://github.com/lobehub/lobe-analytics/issues
[github-issues-shield]: https://img.shields.io/github/issues/lobehub/lobe-analytics?color=ff80eb&labelColor=black&style=flat-square
[github-license-link]: https://github.com/lobehub/lobe-analytics/blob/master/LICENSE
[github-license-shield]: https://img.shields.io/github/license/lobehub/lobe-analytics?color=white&labelColor=black&style=flat-square
[github-releasedate-link]: https://github.com/lobehub/lobe-analytics/releases
[github-releasedate-shield]: https://img.shields.io/github/release-date/lobehub/lobe-analytics?labelColor=black&style=flat-square
[github-stars-link]: https://github.com/lobehub/lobe-analytics/network/stargazers
[github-stars-shield]: https://img.shields.io/github/stars/lobehub/lobe-analytics?color=ffcb47&labelColor=black&style=flat-square
[npm-release-link]: https://www.npmjs.com/package/@lobehub/analytics
[npm-release-shield]: https://img.shields.io/npm/v/@lobehub/analytics?color=369eff&labelColor=black&logo=npm&logoColor=white&style=flat-square
[pr-welcome-link]: https://github.com/lobehub/lobe-analytics/pulls
[pr-welcome-shield]: https://img.shields.io/badge/%F0%9F%A4%AF%20PR%20WELCOME-%E2%86%92-ffcb47?labelColor=black&style=for-the-badge
[profile-link]: https://github.com/lobehub