@bradsearch/analytics-core
v1.0.5
Published
Pure TypeScript analytics library for BradSearch with Umami integration
Readme
@bradsearch/analytics-core
A modern, type-safe TypeScript library for analytics tracking with Umami integration. This core package provides pure JavaScript functionality for tracking search, autocomplete, and e-commerce events.
Features
- Type-Safe: Full TypeScript support with comprehensive type definitions
- Flexible: Works with Umami Analytics out of the box, easily extensible to other providers
- Lightweight: Zero dependencies, small bundle size
- Well-Tested: 100% test coverage on all source code
- Framework-Agnostic: Pure TypeScript/JavaScript, works anywhere
- Enrichment: Automatic event enrichment with identity, cart, and correlation data
- Debouncing: Built-in utilities for debouncing query tracking
Installation
npm install @bradsearch/analytics-coreQuick Start
import { AnalyticsTracker } from "@bradsearch/analytics-core";
// Create a tracker instance
const tracker = new AnalyticsTracker({
identity: {
userId: "user-123",
customerId: "456",
isRegistered: true,
},
cart: {
cartId: "cart-789",
cartTotal: 150.0,
itemCount: 3,
},
debug: true, // Enable debug logging in development
});
// Track autocomplete response
tracker.trackAutocompleteResponse({
query: "laptop",
productIds: ["prod-1", "prod-2", "prod-3"],
resultCount: 3,
});
// Track product click
tracker.trackAutocompleteProductClick({
productId: "prod-1",
query: "laptop",
position: 0,
});
// Track add to cart
tracker.trackAddToCart({
productId: "prod-1",
quantity: 1,
price: 999.99,
});API Reference
AnalyticsTracker
The main class for tracking analytics events.
Constructor
new AnalyticsTracker(config?: AnalyticsConfig)Configuration Options:
interface AnalyticsConfig {
provider?: TrackingProvider; // Custom provider (defaults to UmamiProvider)
identity?: IdentityData; // User identity for enrichment
cart?: CartData; // Cart data for enrichment
debug?: boolean; // Enable debug logging
}Tracking Methods
Autocomplete Events
trackAutocompleteResponse(data) Track when autocomplete search results are returned.
tracker.trackAutocompleteResponse({
query: string;
productIds: string[];
resultCount?: number;
});trackAutocompleteProductClick(data) Track when a user clicks a product in autocomplete results.
tracker.trackAutocompleteProductClick({
productId: string;
query?: string;
position?: number;
});trackAutocompleteSuggestedQueryClick(data) Track when a user clicks a suggested query (e.g., "Did you mean...").
tracker.trackAutocompleteSuggestedQueryClick({
suggestedQuery: string;
originalQuery: string;
position?: number;
});trackAutocompleteCategoryClick(data) Track when a user clicks a category in autocomplete.
tracker.trackAutocompleteCategoryClick({
category: string;
query: string;
field?: string;
});trackAutocompleteFacetClick(data) Track when a user clicks a facet/filter in autocomplete.
tracker.trackAutocompleteFacetClick({
field: string;
value: string;
query: string;
});Search Page Events
trackViewSearch(data) Track when a search results page loads.
tracker.trackViewSearch({
query: string;
productIds: string[];
resultCount?: number;
filters?: Record<string, string[]>;
});trackSearchProductClick(data) Track when a user clicks a product on the search results page.
tracker.trackSearchProductClick({
productId: string;
query: string;
position?: number;
});E-commerce Events
trackAddToCart(data) Track when a product is added to the cart.
tracker.trackAddToCart({
productId: string;
quantity: number;
productAttributeId?: string;
cartId?: string;
price?: number;
});trackRemoveFromCart(data) Track when a product is removed from the cart.
tracker.trackRemoveFromCart({
productId: string;
productAttributeId?: string;
quantity?: number;
});trackUpdateProduct(data) Track when a product's attributes are updated.
tracker.trackUpdateProduct({
productAttributeId: string;
quantity?: number;
newPrice?: number;
});Configuration Methods
updateIdentity(identity: IdentityData) Update the user identity data.
tracker.updateIdentity({
userId: "new-user-123",
isRegistered: true,
});updateCart(cart: CartData) Update the cart data.
tracker.updateCart({
cartId: "cart-new",
cartTotal: 250.5,
itemCount: 5,
});setCorrelationId(requestId: string) Set a correlation ID for distributed tracing.
tracker.setCorrelationId("req-abc-123");addEnrichmentMiddleware(middleware: Function) Add custom enrichment middleware.
tracker.addEnrichmentMiddleware((payload) => ({
...payload,
customField: "custom-value",
}));Advanced Usage
Using ConsoleProvider for Development
The ConsoleProvider logs all events to the console instead of sending to Umami:
import { AnalyticsTracker, ConsoleProvider } from "@bradsearch/analytics-core";
const tracker = new AnalyticsTracker({
provider: new ConsoleProvider(),
});
// Events will be logged to console instead of sent to Umami
tracker.trackAddToCart({
productId: "test-product",
quantity: 1,
});Event Enrichment
All tracked events are automatically enriched with:
- Identity Data: User and customer information
- Cart Data: Shopping cart state
- Correlation Data: Request correlation IDs
// Configure enrichment at initialization
const tracker = new AnalyticsTracker({
identity: {
userId: "user-123",
customerId: "456",
isRegistered: true,
sessionId: "session-xyz",
},
cart: {
cartId: "cart-789",
cartTotal: 150.0,
itemCount: 3,
},
});
// Events will automatically include this data
tracker.trackSearchProductClick({
productId: "prod-1",
query: "laptop",
});
// Tracked event will include identity, and cart dataCustom Enrichment Middleware
Add custom logic to enrich all events:
tracker.addEnrichmentMiddleware((payload) => ({
...payload,
sessionStart: Date.now(),
userAgent: navigator.userAgent,
referrer: document.referrer,
}));Umami Integration
This library integrates with Umami Analytics via the window.umami global object. Make sure Umami is loaded before tracking events:
<script
defer
src="https://analytics.example.com/script.js"
data-website-id="your-website-id"
></script>The library will automatically detect if Umami is available and log warnings in debug mode if it's not.
Event Mapping
| Method | Umami Event Name | Description |
| -------------------------------------- | ------------------------------------------- | -------------------------------- |
| trackAutocompleteResponse | search-autocomplete-response | Search results returned |
| trackAutocompleteProductClick | search-autocomplete-product-click | Product clicked in autocomplete |
| trackAutocompleteSuggestedQueryClick | search-autocomplete-suggested-query-click | Suggested query clicked |
| trackAutocompleteCategoryClick | search-autocomplete-category-click | Category clicked in autocomplete |
| trackAutocompleteFacetClick | search-autocomplete-facet-click | Facet/filter clicked |
| trackViewSearch | view-search | Search results page viewed |
| trackSearchProductClick | search-product-click | Product clicked on search page |
| trackAddToCart | add-to-cart | Product added to cart |
| trackRemoveFromCart | remove-from-cart | Product removed from cart |
| trackUpdateProduct | update-product | Product attributes updated |
Development
Running Tests
npm test # Run tests once
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage reportBuilding
npm run build # Build CommonJS and ESM bundles
npm run dev # Build in watch modeLinting
npm run lint # Run ESLintPackage Exports
The package exports both CommonJS and ESM formats:
- CommonJS:
dist/index.js - ESM:
dist/index.esm.js - TypeScript Types:
dist/index.d.ts
Browser Support
Works in all modern browsers that support ES2020. Requires window object for Umami integration.
License
MIT
Author
BradSearch - [email protected]
Authentication
Login to npm
# Login with your npm account
npm login
# Verify authentication
npm whoamiSwitch npm User
# Logout current user
npm logout
# Login with different account
npm login --registry https://registry.npmjs.org/Publishing to npm
First Time Publication
# Publish as public package (required for scoped packages)
npm publish --access publicSubsequent Releases
# Regular publish (after version bump)
npm publishPublishing Beta/Alpha Versions
# Tag as beta
npm version prerelease --preid=beta
npm publish --tag beta
# Tag as alpha
npm version prerelease --preid=alpha
npm publish --tag alpha