rozmova-analytics
v1.1.41
Published
A collection of JavaScript functions for Rozmova analytics
Maintainers
Readme
rozmova-analytics
A lightweight JavaScript analytics library designed to streamline event tracking, user identification, and common analytics parameter management. This package integrates with Mixpanel, Google Analytics, Customer.io, and Microsoft Clarity to provide seamless data collection and insights.
Installation
Install the package using npm:
npm install rozmova-analyticsAlternatively, you can include the library via jsDelivr to use in browser:
<script src="https://cdn.jsdelivr.net/npm/rozmova-analytics/dist/index.umd.js"></script>Usage
Import the library in your project and initialize it:
import Analytics from "rozmova-analytics";
// Initialize the library
Analytics.init({ locale: "en", platform: "web", isClearly: true });
// Set user
Analytics.setUser("user-id-123", {
email: "[email protected]",
name: "John Doe",
numberOfSessions: 5,
locale: "en",
phone: "+1234567890",
isB2B: false
});
// Track an event
Analytics.trackEvent("button_click", { button_name: "Sign Up" });Or use in browser:
// Initialize the library
window.Analytics.init({ locale: "en", platform: "web" });
// Set user
window.Analytics.setUser("user-id-123", {
email: "[email protected]",
name: "John Doe",
numberOfSessions: 1,
locale: "en"
});
// Track an event
window.Analytics.trackEvent("button_click", { button_name: "Sign Up" });API Reference
init(config?)
Initializes the analytics library, setting up Mixpanel, Google Analytics, Customer.io, and Microsoft Clarity integrations.
Parameters:
config.isProd?: boolean- Whether the environment is production (default: true)config.locale?: string- The locale for analytics data (default: auto-detected or "uk")config.platform?: string- The platform identifier (default: "web")config.isClearly?: boolean- Whether to enable Clearly-specific features like cookie consent bannerconfig.config?: object- Initial configuration object with userId and emailconfig.config.userId?: string- Initial user IDconfig.config.email?: string- Initial user email
Example:
Analytics.init({
isProd: true,
locale: "en",
platform: "web",
isClearly: true,
config: {
userId: "user-123",
email: "[email protected]"
}
});trackEvent(eventName, properties?, services?)
Tracks an event across the specified analytics providers.
Parameters:
eventName: string- The name of the event to trackproperties?: EventParams- Additional event properties (optional)services?: object- Which services to track to (optional, default: all enabled)ga?: boolean- Google Analytics (default: true)mixpanel?: boolean- Mixpanel (default: true)customerIO?: boolean- Customer.io (default: true)
Example:
// Track to all services
Analytics.trackEvent("purchase", {
product_id: "123",
price: 29.99,
currency: "USD"
});
// Track to specific services only
Analytics.trackEvent("newsletter_signup", {
source: "footer"
}, {
ga: true,
mixpanel: false,
customerIO: true
});setUser(userId, userParams)
Associates a user with the provided user ID and sets user properties across all analytics providers.
Parameters:
userId: string- Unique user identifieruserParams: object- User propertiesemail: string- User's email addressname: string- User's full namenumberOfSessions: number- Number of user sessionslocale: string- User's localephone?: string- User's phone number (optional)isB2B?: boolean- Whether the user is a business user (optional)CIOParams?: EventParams- Additional properties for Customer.io (optional)mixpanelParams?: Dict- Additional properties for Mixpanel (optional)
Example:
Analytics.setUser("user-456", {
email: "[email protected]",
name: "Jane Doe",
numberOfSessions: 3,
locale: "en",
phone: "+1234567890",
isB2B: true,
CIOParams: {
custom_field: "value"
},
mixpanelParams: {
$created: "2024-01-01"
}
});resetUser()
Resets the current user across all analytics providers, clears stored user data, generates a new user ID, and reinitializes the library. Automatically calls init() after reset.
Example:
Analytics.resetUser();setUserTag(key, value)
Sets a user tag in Microsoft Clarity for enhanced user identification and session analysis.
Parameters:
key: string- The tag keyvalue: string- The tag value
Example:
Analytics.setUserTag("user_type", "premium");
Analytics.setUserTag("subscription_plan", "pro");setConfig(params?)
Updates the analytics configuration with new parameters. This is a private method but can be called indirectly through setUser() or resetUser().
Parameters:
params.userId?: string- User ID to set (default: from profile)params.email?: string- User email to set (default: from profile)
Note: This method is called automatically when setting or resetting users. Direct usage is not recommended.
setLocale(newLocale)
Updates the locale for analytics data.
Parameters:
newLocale: string- The new locale to set
Example:
Analytics.setLocale("es");trackPageView(options?)
Tracks a page view event with current page information including title, location, and referrer.
Parameters:
options.referrer?: string- Custom referrer URL (optional, defaults to document.referrer)
Example:
// Track with default referrer
Analytics.trackPageView();
// Track with custom referrer
Analytics.trackPageView({ referrer: "https://example.com" });getCommonParams()
Returns an object with common analytics parameters including device information, browser details, UTM parameters, user data, and session information.
Returns: AnalyticsCommonParams
Example:
const params = Analytics.getCommonParams();
console.log(params.device, params.browser, params.locale);getUserId()
Retrieves the current user ID from cookies, localStorage, or URL query parameters. Generates a new one if not found.
Returns: string
Example:
const userId = Analytics.getUserId();getGAClientId()
Retrieves the Google Analytics client ID asynchronously.
Returns: Promise<string | null>
Example:
const gaClientId = await Analytics.getGAClientId();setGAClientId(clientId)
Sets the Google Analytics client ID.
Parameters:
clientId: string- The GA client ID to set
Example:
Analytics.setGAClientId("1234567890.1234567890");getAttributionProperties(forcedAttributionProperties?)
Retrieves comprehensive attribution properties including funnel info, tracking parameters, and external analytics user information.
Parameters:
forcedAttributionProperties?: ForcedAttributionProperties- Optional forced attribution propertiesforcedAttributionProperties.funnelName?: string- Override funnel name
Returns: Promise<UserAttributionProperties>
Example:
const attribution = await Analytics.getAttributionProperties({
funnelName: "custom_funnel"
});
console.log(attribution.funnelInfo);
console.log(attribution.trackingParams);
console.log(attribution.externalAnalyticsUserInfo);trackFirstPartyEvent(eventName, properties?, forcedAttributionProperties?)
Tracks an event to your first-party analytics endpoint with comprehensive attribution data encoded in headers.
Parameters:
eventName: string- The name of the event to trackproperties?: EventParams- Additional event properties (optional)forcedAttributionProperties?: ForcedAttributionProperties- Optional forced attribution properties
Returns: Promise<Response>
Example:
// Track first-party event
await Analytics.trackFirstPartyEvent("purchase_completed", {
product_id: "123",
price: 29.99
});
// Track with forced attribution
await Analytics.trackFirstPartyEvent("signup", {
source: "landing_page"
}, {
funnelName: "marketing_campaign"
});Analytics Providers
The library integrates with multiple analytics providers out of the box:
Mixpanel
- Event tracking with custom properties
- User identification and profile management
- Automatic page view tracking
- User property registration
Google Analytics 4
- Event tracking with enhanced ecommerce support
- User identification with custom user properties
- Server-side container support
- Automatic ecommerce event handling
Customer.io
- Behavioral event tracking
- User identification and profile management
- Automated messaging and email triggers
Microsoft Clarity
- Session recording and heatmaps
- User tagging for enhanced insights
- Automatic session tracking
Features
Event Queuing
Events tracked before initialization are queued and processed once the library is ready.
Error Handling
Individual service failures don't affect other providers - the library includes comprehensive error handling.
Cookie Consent
Automatic cookie consent banner integration for GDPR compliance when isClearly is enabled.
Meta Browser Detection
Special handling for Meta (Facebook) browsers with automatic URL parameter tracking.
Geo Parameter Storage
Automatic storage and tracking of geographic parameters.
Session Management
Comprehensive session tracking with Google Analytics session IDs and user pseudo IDs.
Browser Support
The package works on modern browsers and supports:
- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
Example Integration
import Analytics from "rozmova-analytics";
// Initialize analytics
Analytics.init({
locale: "en",
platform: "web",
isClearly: true
});
// Track a page view (automatically called during init)
Analytics.trackPageView();
// Set user details
Analytics.setUser("user-456", {
email: "[email protected]",
name: "Jane Doe",
numberOfSessions: 1,
locale: "en",
phone: "+1234567890",
isB2B: false
});
// Track custom events
Analytics.trackEvent("feature_used", {
feature_name: "advanced_search",
user_tier: "premium"
});
// Track first-party event with attribution
await Analytics.trackFirstPartyEvent("purchase", {
product_id: "123",
amount: 99.99
});
// Get attribution properties
const attribution = await Analytics.getAttributionProperties();
console.log(attribution.funnelInfo, attribution.trackingParams);
// Get GA client ID
const gaClientId = await Analytics.getGAClientId();
// Set user tags for Clarity
Analytics.setUserTag("subscription", "premium");
Analytics.setUserTag("user_segment", "power_user");
// Update locale
Analytics.setLocale("fr");
// Reset user on logout
Analytics.resetUser();Configuration
Make sure to configure your analytics provider tokens in your constants file:
// constants.js
export const MIXPANEL_TOKEN = "your-mixpanel-token";
export const GOOGLE_ANALYTICS_ID = "your-ga-measurement-id";
export const CLARITY_ID = "your-clarity-project-id";
export const GA_SERVER_CONTAINER_URL = "your-server-container-url";Common Parameters
The library automatically collects and includes common parameters with every event:
- Device type, browser, and operating system
- User language and locale
- UTM parameters and referrer information
- Session IDs and user pseudo IDs
- Facebook tracking parameters (fbc, fbp)
- Current URL and page information
- User login status and profile data
TypeScript Support
The library includes TypeScript definitions for better development experience:
import Analytics from "rozmova-analytics";
import type {
EventParams,
UserAttributionProperties,
ForcedAttributionProperties
} from "rozmova-analytics";
// Type-safe event tracking
const eventParams: EventParams = {
product_id: "123",
category: "electronics"
};
Analytics.trackEvent("product_view", eventParams);
// Type-safe attribution properties
const attribution: UserAttributionProperties = await Analytics.getAttributionProperties();
// Type-safe first-party event tracking
const forcedAttribution: ForcedAttributionProperties = {
funnelName: "custom_funnel"
};
await Analytics.trackFirstPartyEvent("signup", eventParams, forcedAttribution);Contributing
Contributions are welcome! Please fork the repository and create a pull request with your changes.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License.
