cdp-events-tracker
v1.4.4
Published
cdp-events-tracker is a lightweight TypeScript library that collects and sends user interaction data to your Customer Data Platform (CDP). It supports event queuing, batching, and Beacon API for optimal delivery
Downloads
469
Readme
CDP Events Tracker
A lightweight, framework-agnostic TypeScript library for tracking user sessions, page interactions, and engagement events and forwarding them to a Customer Data Platform (CDP). It handles customer profile lifecycle, session and interaction management, scroll depth tracking, UTM attribution, and DOM-level event capture — all from a single initialisation call.
Installation
npm install cdp-events-trackerQuick start
import {
CDPEventsTracker,
EnvironmentType,
PageActionPoint,
CustomEvents,
EventType,
PageMetadata,
} from "cdp-events-tracker";
const tracker = new CDPEventsTracker(
true, // shouldCollectUserEngagementData
"NATION_AFRICA", // platform
"website", // channel
EnvironmentType.production, // environment
"https://your-cdp-api.com/", // baseURL
"your-x-api-key", // xAPIKey
{
articleId: "5095576",
articleTitle: "Uniting Kenya through sport",
articleTags: "Prime, Sports, Inspire Me",
authors: "Elias Makori",
articlePublishDate: "2025-06-26T06:40:37Z",
articleThumbNail: "https://example.com/image.jpg",
site: "Nation",
rootTitle: "Kenya",
premium: true,
isPuzzlesPage: false,
pageTitle: "Athletics",
}
);If
shouldCollectUserEngagementDataisfalse, the tracker exits immediately and no data is collected or sent.
Constructor parameters
| Parameter | Type | Description |
|---|---|---|
| shouldCollectUserEngagementData | boolean | Master kill switch. Set to false to disable all tracking. |
| platform | string | The publishing platform identifier, e.g. "NATION_AFRICA". |
| channel | string | The delivery channel, e.g. "web" or "mobile". |
| environment | EnvironmentType | EnvironmentType.production or EnvironmentType.beta. Controls the localStorage key namespace. |
| baseURL | string | Base URL of your CDP API, including trailing slash. |
| xAPIKey | string | API key sent as the x-api-key header on every request. |
| pageMetadata | PageMetadata | Metadata describing the current page. See PageMetadata below. |
PageMetadata
interface PageMetadata {
articleId: string;
articleTitle: string;
articleTags: string; // comma-separated, e.g. "Sports, Prime"
authors: string;
articlePublishDate: string; // ISO 8601
articleThumbNail: string;
pageSection: string;
pageSubSection?: string;
site: string;
rootTitle: string;
premium: boolean;
isPuzzlesPage: boolean;
pageTitle: string;
contentType?: string;
}Dispatching events programmatically
Use tracker.dispatchEvent() to send events from your application code. The method accepts any value from the PageActionPoint, CustomEvents, or EventType enums, plus an optional metadata payload.
tracker.dispatchEvent(eventType, eventMetadata?)Custom events (with payloads)
These events carry structured data and trigger dedicated CDP operations.
New subscription purchase
tracker.dispatchEvent(CustomEvents.newSubscriptionPurchase, {
purchase_id: "c1aab9d7-9b14-48da-9ff3-89cdffc6f47a",
purchase_date: "2025-06-26T06:40:37Z",
expiry_date: "2025-06-30T06:40:37Z",
amount_paid: 1500,
currency: "KES",
package_type: "ANNUAL",
payment_option: "mpesa",
recurrent: true,
});New subscription lead
tracker.dispatchEvent(CustomEvents.newLead, {
page_url: window.location.href,
article_id: "5095576",
trigger_action: "paywall_subscribe_button_click",
platform: "NATION_AFRICA",
});Anonymous to registered conversion
tracker.dispatchEvent(CustomEvents.anonymousToRegisteredConversion, {
previous_state: "anonymous",
current_state: "registered",
conversion_time: new Date().toISOString(),
});Newsletter subscription
tracker.dispatchEvent(CustomEvents.newsLetterSubscription, {
newsletter_id: "newsletter_001",
subscription_status: "active",
subscribed_at: new Date(),
type: "weekly",
title: "Nation Weekly Digest",
isPremium: false,
});Newsletter unsubscription
tracker.dispatchEvent(CustomEvents.newsLetterUnsubscription, {
newsletter_id: "newsletter_001",
subscription_status: "inactive",
unsubscribed_at: new Date(),
});Engagement events (no payload)
All other event types — PageActionPoint and EventType values — are recorded as engagement events tied to the active page interaction, capturing the current scroll depth and time-on-page automatically.
tracker.dispatchEvent(PageActionPoint.navbarSubscribeBtnClick);
tracker.dispatchEvent(EventType.premiumArticleView);
tracker.dispatchEvent(PageActionPoint.mpesaPaymentSuccess);Enums
PageActionPoint
Granular UI action events, primarily covering the subscription and payment funnel.
| Value | Description |
|---|---|
| navbarSubscribeBtnClick | Subscribe button in the navigation bar |
| articleSubscribeBtnClick | Subscribe button within an article |
| paywallSubscribeBtnClick (via EventType) | Subscribe button on the paywall |
| annualPackageSelected | Annual subscription package selected |
| quarterlyPackageSelected | Quarterly package selected |
| monthlyPackageSelected | Monthly package selected |
| weeklyPackageSelected | Weekly package selected |
| dailyPackageSelected | Daily package selected |
| mpesaPaymentModeSelected | M-Pesa chosen as payment method |
| mpesaSTKPushTriggeredSuccessfully | M-Pesa STK push confirmed |
| mpesaPaymentSuccess | M-Pesa payment completed |
| dpoPurchaseVerifiedSuccessfully | DPO purchase verified |
| adClick | An ad unit was clicked |
| retentionPopupSubscribeBtnClick | Subscribe clicked from retention popup |
| winBackPopUpSubscribeBtnClick | Subscribe clicked from win-back popup |
| adBlockerSubscribeBtnClick | Subscribe clicked from adblocker popup |
| exitIntentPopUPSubscribeBtnClick | Subscribe clicked from exit-intent popup |
| singleNewsLetterSubscribeBtnClick | Newsletter subscribe button clicked |
| singleNewsLetterUnSubscribeBtnClick | Newsletter unsubscribe button clicked |
EventType
Higher-level behavioural and funnel events.
| Value | Description |
|---|---|
| premiumArticleView | A premium article was viewed |
| paywallSubscribeButtonClick | Paywall subscribe button clicked |
| navbarSubscribeButtonClick | Navbar subscribe button clicked |
| subscriptionCheckout | Subscription checkout initiated |
| subsbscriptionPaymentSuccess | Payment completed successfully |
| subsbscriptionPaymentFailure | Payment failed |
| googleButtonLogin | Login via Google button |
| googleOneTapLogin | Login via Google One Tap |
| emailAndPasswordLogin | Login via email and password |
| disqusComment | User posted a Disqus comment |
| disqusReaction | User reacted to a Disqus post |
| nearExpiryRenewSubscriptionButonClick | Renew clicked near subscription expiry |
| expiredRecentlyRenewSubscriptionButonClick | Renew clicked after recent expiry |
| payPerArticleBtnClick | Pay-per-article button clicked |
| mtaaWanguArticleClick | Mtaa Wangu article clicked |
CustomEvents
Events that trigger dedicated CDP operations with structured payloads.
| Value | CDP operation |
|---|---|
| newLead | saveSubscriptionLead |
| newSubscriptionPurchase | registerSubscriptionPurchase |
| newsLetterSubscription | registerNewsLetterSubscription |
| newsLetterUnsubscription | registerNewsLetterUnSubscription |
| anonymousToRegisteredConversion | registerCustomerConversion |
EnvironmentType
| Value | Effect |
|---|---|
| EnvironmentType.production | Uses prodCDPCustomerProfile as the localStorage key |
| EnvironmentType.beta | Uses betaV2CDPCustomerProfile as the localStorage key |
DOM-based event tracking
The tracker automatically scans the DOM for elements with a data-cdp-role attribute and attaches the appropriate event listeners — click for most elements, submit for forms.
Attribute specification
Add data-cdp-role to identify the element and data-cdp-event to name the event it should fire:
<a
href="https://example.com/subscribe"
data-cdp-role="navbar_subscribe-btn"
data-cdp-event="navbar_subscribe_btn_click"
>
Subscribe
</a>For elements that trigger a subscription lead flow (paywall, navbar, adblocker, retention, win-back, and exit-intent subscribe buttons, and pay-per-article), the tracker automatically:
- Intercepts the click and prevents default navigation
- Saves a subscription lead event to the CDP and retrieves the
leadEventId - Appends
?leadEvent=<id>to the target href - Redirects after a short delay
An optional data-cdp-campaign attribute can be added to pass a campaign identifier into the lead event.
<a
href="https://example.com/subscribe"
data-cdp-role="paywall_subscribe-btn"
data-cdp-event="paywall_subscribe_button_click"
data-cdp-campaign="summer_promo_2025"
>
Subscribe
</a>Supported data-cdp-role values
data-cdp-role="navbar_subscribe-btn"
data-cdp-role="paywall_subscribe-btn"
data-cdp-role="article_author-profile-link"
data-cdp-role="navbar_search-btn"
data-cdp-role="navbar_signin-btn"
data-cdp-role="article_newsletter-subscribe-form"
data-cdp-role="universal_ad-wrapper"
data-cdp-role="universal_ad-script"What happens automatically
Once initialised, the tracker manages the full customer and session lifecycle without any additional calls:
- Customer profile — creates an anonymous CDP profile on first visit; recovers and merges it on login; updates it when subscription status changes
- Session — starts a session on page load, ends it after 10 minutes of inactivity or when the tab is closed
- Page interaction — records a new interaction on every page load and on tab visibility restore; ends it on tab hide or close
- Article metadata — attached automatically to any interaction on a page with an
articleId - Scroll depth — tracks 25%, 50%, 75%, and 100% milestones; reported on interaction end
- UTM attribution — reads
utm_source,utm_medium, andutm_campaignfrom the URL query string and attaches them to both sessions and interactions - Session viability — on load, stale sessions older than 30 minutes stored in localStorage are detected and terminated via the API
Error handling
All HTTP errors are mapped to typed error classes exported from the library:
| Class | HTTP status | When thrown |
|---|---|---|
| UnauthorizedError | 401 | Invalid or missing API key / auth token |
| NotFoundError | 404 | Resource does not exist |
| ValidationError | 400 | Malformed request payload |
| TechnicalError | 500 | Internal server error |
| RequestTimeoutError | — | Request exceeded the timeout threshold |
import { NotFoundError, ValidationError } from "cdp-events-tracker";
try {
await tracker.dispatchEvent(CustomEvents.newLead, source);
} catch (err) {
if (err instanceof ValidationError) {
// handle bad payload
}
}TypeScript support
The library is written in TypeScript and ships with full type definitions. All event payloads, DTOs, and enums are exported directly.
import {
PageMetadata,
NewPurchasePayload,
NewsLetterSubscriptionPayload,
ConversionSource,
EnvironmentType,
PageActionPoint,
CustomEvents,
EventType,
AUTHProvider,
} from "cdp-events-tracker";