CDP Lite SDK for tracking events and users - Customer Data Platform
npm install cdp-lite-sdkCustomer Data Platform SDK for tracking events and users. A lightweight, powerful analytics SDK for JavaScript/TypeScript applications.


- Features
- Installation
- Quick Start
- Configuration
- Security Features
- ID Management
- User Tracking
- Core Methods
- Advanced Usage
- React Integration
- TypeScript Support
- API Reference
- Examples
- Troubleshooting
---
- ✅ Event Tracking - Track custom events with properties
- ✅ User Identification - Identify and track users
- 🔒 Data Encryption - AES-256-CBC encryption for sensitive user data
- 🔐 Request Signing - HMAC-SHA256 signatures for API security
- ✅ Batch Processing - Auto-batch events for optimal performance
- ✅ Device Detection - Auto-detect device information
- ✅ Anonymous Tracking - Track users before identification
- ✅ Page/Screen Views - Built-in page and screen tracking
- ✅ TypeScript Support - Full TypeScript definitions
- ✅ Framework Agnostic - Works with React, Vue, Angular, Vanilla JS
- ✅ Browser & Node.js - Universal JavaScript support
- ✅ Queue Management - Smart event queueing and flushing
- ✅ Debug Mode - Easy debugging with console logs
---
``bash`
npm install cdp-lite-sdk
`bash`
yarn add cdp-lite-sdk
`html`
---
`javascript
import CdpLiteSdk from 'cdp-lite-sdk';
// Initialize SDK with security
const cdp = new CdpLiteSdk({
apiKey: 'your-api-key',
secretKey: 'your-secret-key', // Required for encryption & signatures
source: 'YourApp',
serviceName: 'YourService',
isTest: true,
debug: true
});
// Identify user (sensitive data auto-encrypted)
cdp.identify('user_123', {
full_name: 'John Doe',
email: 'john@example.com',
phone: '0901234567'
});
// Track event (auto-signed with HMAC)
cdp.track('button_clicked', {
button_name: 'Sign Up',
page: 'Landing'
});
`
`javascript
const CdpLiteSdk = require('cdp-lite-sdk');
const cdp = new CdpLiteSdk({
apiKey: 'your-api-key',
source: 'BackendService'
});
`
`html`
---
`javascript`
const cdp = new CdpLiteSdk({
// Required
apiKey: 'string', // Your API key
// Security (Recommended)
secretKey: 'string', // Secret key for encryption & signatures
enableEncryption: boolean, // Enable traits encryption (default: true)
// Optional
source: 'string', // Source name (default: 'Web')
serviceName: 'string', // Service name (default: 'DefaultService')
baseUrl: 'string', // API base URL
isTest: boolean, // Test mode (default: false)
debug: boolean, // Enable debug logs (default: false)
batchSize: number, // Events per batch (default: 10)
batchInterval: number, // Batch interval in ms (default: 5000)
autoTrackDevice: boolean // Auto detect device (default: true)
});
#### Development
`javascript`
const cdp = new CdpLiteSdk({
apiKey: 'dev-api-key',
secretKey: 'dev-secret-key',
source: 'MyApp',
serviceName: 'MyService',
baseUrl: 'https://stg-ingestlog.vietcredit.com.vn',
isTest: true,
debug: true,
batchSize: 5,
batchInterval: 3000
});
#### Production
`javascript`
const cdp = new CdpLiteSdk({
apiKey: process.env.CDP_API_KEY,
secretKey: process.env.CDP_SECRET_KEY,
source: 'MyApp',
serviceName: 'MyService',
baseUrl: 'https://vconnect.vietcredit.com.vn',
isTest: false,
debug: false,
batchSize: 20,
batchInterval: 10000
});
---
SDK automatically encrypts sensitive user data using AES-256-CBC before sending:
`javascript`
// Sensitive data is automatically encrypted
cdp.identify('user_123', {
email: 'user@example.com', // Encrypted
phone: '0901234567', // Encrypted
idcard: '001234567890', // Encrypted
// Other fields are not encrypted
city: 'Hanoi',
age: 30
});
All API requests are signed with HMAC-SHA256 for authentication:
``
X-Signatures = Base64(HMAC-SHA256(X-Source + "|" + X-Timestamp + "|" + Payload))
`javascript`
const cdp = new CdpLiteSdk({
apiKey: process.env.CDP_API_KEY,
secretKey: process.env.CDP_SECRET_KEY, // Required for security
enableEncryption: true // Default: true
});
📖 See SECURITY.md for complete security documentation.
---
CDP Lite SDK manages 5 types of IDs for comprehensive user tracking:
| ID | Description | Persistence | Usage |
|----|-------------|-------------|-------|
| user_id | User identifier | Persistent | Set on login |
| profile_id | CDP profile ID | Persistent | From API response |
| anonymous_id | Anonymous visitor | Persistent | Auto-generated |
| device_id | Device identifier | Persistent | Cross-session tracking |
| session_id | Session identifier | Per session | Single visit |
`javascript
// 1. User logs in
await cdp.identifyUser('user_123', {
email: 'user@example.com'
});
// 2. SDK calls /v1/profiles/track
// Response: { profile_id: 137455779753893888 }
// 3. Profile ID stored automatically
console.log(cdp.getProfileId()); // 137455779753893888
// 4. All events include profile_id
cdp.track('purchase', { amount: 100 });
// Event includes: profile_id, device_id, session_id
`
`javascript`
const ids = cdp.getUserIdentities();
console.log(ids);
// {
// user_id: 'user_123',
// profile_id: 137455779753893888,
// anonymous_id: '550e8400-...',
// device_id: '7a6f8b2e-...',
// session_id: 'abc12345-...'
// }
`javascript
// Get specific IDs
cdp.getUserId() // User ID
cdp.getProfileId() // Profile ID (from API)
cdp.getDeviceId() // Device ID (persistent)
cdp.getSessionId() // Session ID (per session)
cdp.anonymousId // Anonymous ID
// Get all identities
cdp.getUserIdentities() // All IDs in one object
`
📖 Complete Guide: IDS.md
---
CDP Lite SDK provides MoEngage-compatible methods for user tracking:
`javascript
// Login/Identify user
await cdp.identifyUser('user_123', {
full_name: 'John Doe',
email: 'john@example.com',
phone: '+84901234567'
});
// Update attributes with fluent API
cdp
.add_first_name('John')
.add_last_name('Doe')
.add_email('john@example.com')
.add_mobile('+84901234567')
.add_gender('Male')
.add_birthday(new Date(1990, 0, 1));
// Custom attributes
cdp.add_user_attribute('membership_level', 'Gold');
cdp.add_user_attributes({
loyalty_points: 1500,
vip_status: true
});
// Get user info
const identities = cdp.getUserIdentities();
const email = cdp.getUserAttribute('email');
// Logout
await cdp.destroy_session();
`
| Method | Description |
|--------|-------------|
| identifyUser(id, traits?) | Login/identify user |add_first_name(value)
| | Add first name |add_last_name(value)
| | Add last name |add_user_name(value)
| | Add full name |add_email(value)
| | Add email |add_mobile(value)
| | Add phone |add_gender(value)
| | Add gender |add_birthday(value)
| | Add date of birth |add_idcard(value)
| | Add ID card |add_address(value)
| | Add address |add_user_attribute(name, value)
| | Add custom attribute |getUserIdentities()
| | Get user identities |getUserAttribute(name)
| | Get specific attribute |destroy_session()
| | Logout user |
📖 Complete Guide: USER-TRACKING.md
---
Track custom events with properties.
`javascript`
cdp.track(eventName, properties, options);
Parameters:
- eventName (string) - Name of the eventproperties
- (object) - Event properties (optional)options
- (object) - Additional options (optional)
Example:
`javascript
// Basic event
cdp.track('purchase_completed', {
product_id: 'PROD123',
amount: 99.99,
currency: 'USD'
});
// With loan code
cdp.track('loan_application', {
amount: 50000000,
term: 12
}, {
loanCode: 'LOAN123'
});
// With campaign data
cdp.track('signup', {
method: 'email'
}, {
campaign: {
source: 'facebook',
medium: 'cpc',
campaign: 'summer_sale'
}
});
`
Identify users and set their attributes.
`javascript`
cdp.identify(userId, traits);
Parameters:
- userId (string) - Unique user identifiertraits
- (object) - User attributes (optional)
Example:
`javascript`
cdp.identify('user_123', {
// Sensitive fields (auto-encrypted)
full_name: 'Nguyen Van A',
first_name: 'A',
last_name: 'Nguyen Van',
email: 'user@example.com',
phone: '+84901234567',
idcard: '001234567890',
dob: '1990-01-01',
gender: 'male',
address: '123 ABC Street, Hanoi',
religion: 'Buddhism',
// Non-sensitive fields (not encrypted)
age: 30,
city: 'Hanoi',
plan: 'premium'
});
Sensitive Fields (Auto-Encrypted):
- full_name, first_name, last_nameidcard
- , old_idcardphone
- , emailgender
- , dobaddress
- , religion
Track page views (for web applications).
`javascript`
cdp.page(pageName, properties);
Example:
`javascript
cdp.page('Home', {
url: window.location.href,
title: document.title,
referrer: document.referrer
});
cdp.page('Product Details', {
product_id: 'PROD123',
category: 'Electronics'
});
`
Track screen views (for mobile applications).
`javascript`
cdp.screen(screenName, properties);
Example:
`javascript
cdp.screen('Home Screen', {
tab: 'featured'
});
cdp.screen('Product Detail', {
product_id: 'PROD123'
});
`
Update user attributes without re-identifying.
`javascript`
cdp.setUserAttributes(traits);
Example:
`javascript`
cdp.setUserAttributes({
subscription: 'premium',
last_login: new Date().toISOString(),
total_purchases: 5
});
Manually set device information.
`javascript`
cdp.setDeviceInfo(deviceInfo);
Example:
`javascript`
cdp.setDeviceInfo({
platform: 'ios',
brand: 'Apple',
model: 'iPhone 14 Pro',
app_version: '2.1.0',
os_version: '16.3'
});
Manually send all queued events immediately.
`javascript`
await cdp.flush();
Example:
`javascript
// Add multiple events
cdp.track('event_1');
cdp.track('event_2');
cdp.track('event_3');
// Send all immediately
await cdp.flush();
`
Clear user data (useful for logout).
`javascript`
cdp.reset();
Example:
`javascript`
function handleLogout() {
cdp.reset();
// Redirect to login page
}
Clean up resources when done.
`javascript`
cdp.destroy();
---
SDK automatically batches events for efficiency.
`javascript
const cdp = new CdpLiteSdk({
apiKey: 'your-api-key',
batchSize: 20, // Send after 20 events
batchInterval: 10000 // Or after 10 seconds
});
// These will be batched
cdp.track('event_1');
cdp.track('event_2');
cdp.track('event_3');
// ... will send when 20 events or 10 seconds
`
Send events immediately:
`javascript`
const cdp = new CdpLiteSdk({
apiKey: 'your-api-key',
batchSize: 1 // Send immediately
});
`javascript`
try {
await cdp.track('event_name', { data: 'value' });
console.log('Event tracked successfully');
} catch (error) {
console.error('Failed to track event:', error);
}
`javascript`
cdp.track('checkout', {
total: 299.99
}, {
context: {
ip: '192.168.1.1',
locale: 'vi_VN',
timezone: 'Asia/Ho_Chi_Minh',
user_agent: navigator.userAgent
}
});
---
`javascript
// analytics.js
import CdpLiteSdk from 'cdp-lite-sdk';
export const cdp = new CdpLiteSdk({
apiKey: process.env.REACT_APP_CDP_API_KEY,
source: 'WebApp',
serviceName: 'MyApp',
debug: process.env.NODE_ENV === 'development'
});
export default cdp;
`
`javascript
// useAnalytics.js
import { useCallback } from 'react';
import { cdp } from './analytics';
export function useAnalytics() {
const trackEvent = useCallback((eventName, properties) => {
cdp.track(eventName, properties);
}, []);
const identifyUser = useCallback((userId, traits) => {
cdp.identify(userId, traits);
}, []);
const trackPageView = useCallback((pageName, properties) => {
cdp.page(pageName, properties);
}, []);
return { trackEvent, identifyUser, trackPageView };
}
`
`javascript
// Component.jsx
import { useAnalytics } from './useAnalytics';
function ProductPage({ product }) {
const { trackEvent, trackPageView } = useAnalytics();
useEffect(() => {
trackPageView('Product Detail', {
product_id: product.id,
product_name: product.name
});
}, [product]);
const handleAddToCart = () => {
trackEvent('add_to_cart', {
product_id: product.id,
price: product.price
});
};
return (
$3
`javascript
// App.jsx
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { cdp } from './analytics';function App() {
const location = useLocation();
useEffect(() => {
cdp.page(location.pathname, {
path: location.pathname,
search: location.search
});
}, [location]);
return ;
}
`---
🎯 TypeScript Support
Full TypeScript support with type definitions.
`typescript
import CdpLiteSdk, { CdpConfig, EventProperties, UserTraits } from 'cdp-lite-sdk';const config: CdpConfig = {
apiKey: 'your-api-key',
source: 'MyApp',
debug: true
};
const cdp = new CdpLiteSdk(config);
const userTraits: UserTraits = {
name: 'John Doe',
email: 'john@example.com',
age: 30
};
cdp.identify('user_123', userTraits);
const eventProps: EventProperties = {
product_id: '123',
price: 99.99,
currency: 'USD'
};
cdp.track('purchase', eventProps);
`---
📖 API Reference
$3
`typescript
const config: CdpLiteSdk = {
apiKey: 'your-api-key',
secretKey: 'your-secret-key', // Required for security features
source: 'YourApp',
serviceName: 'YourService',
enableEncryption: true, // Enable encryption (default: true)
debug: true
}const sdk = new CdpLiteSdk(config)
`$3
| Method | Parameters | Return | Description |
|--------|-----------|--------|-------------|
|
track() | eventName, properties?, options? | Promise | Track an event |
| identify() | userId, traits? | Promise | Identify a user |
| page() | pageName, properties? | Promise | Track page view |
| screen() | screenName, properties? | Promise | Track screen view |
| setUserAttributes() | traits | Promise | Update user attrs |
| setDeviceInfo() | deviceInfo | void | Set device info |
| flush() | - | Promise | Flush event queue |
| reset() | - | void | Reset user data |
| destroy() | - | void | Cleanup resources |---
💡 Examples
$3
`javascript
// Product viewed
cdp.track('product_viewed', {
product_id: 'SKU123',
product_name: 'iPhone 14',
price: 20000000,
currency: 'VND',
category: 'Electronics'
});// Add to cart
cdp.track('add_to_cart', {
product_id: 'SKU123',
quantity: 1,
price: 20000000
});
// Checkout
cdp.track('checkout_started', {
cart_total: 20000000,
item_count: 1
});
// Purchase
cdp.track('purchase_completed', {
order_id: 'ORDER789',
total: 20000000,
currency: 'VND',
payment_method: 'credit_card'
});
`$3
`javascript
// Start application
cdp.track('loan_application_started', {
loan_amount: 50000000,
loan_term: 12,
loan_type: 'personal'
});// Step completed
cdp.track('application_step_completed', {
step_name: 'personal_info',
step_number: 1
}, {
loanCode: 'LOAN123'
});
// Submit application
cdp.track('loan_application_submitted', {
loan_amount: 50000000,
loan_term: 12
}, {
loanCode: 'LOAN123'
});
`$3
`javascript
// Registration
cdp.track('user_registered', {
method: 'email',
source: 'organic'
});cdp.identify('user_123', {
name: 'John Doe',
email: 'john@example.com',
created_at: new Date().toISOString()
});
// Login
cdp.track('user_logged_in', {
method: 'email'
});
// Logout
cdp.track('user_logged_out');
cdp.reset();
`$3
`javascript
// Form started
cdp.track('form_started', {
form_name: 'contact_form',
form_id: 'contact_123'
});// Field completed
cdp.track('form_field_completed', {
form_name: 'contact_form',
field_name: 'email'
});
// Form submitted
cdp.track('form_submitted', {
form_name: 'contact_form',
fields_count: 5,
time_spent: 120 // seconds
});
`---
🐛 Troubleshooting
$3
Problem: Events are not being tracked
Solutions:
1. Check API key is correct
2. Enable debug mode:
debug: true
3. Check network tab in DevTools
4. Verify baseUrl is correct`javascript
const cdp = new CdpLiteSdk({
apiKey: 'your-api-key',
debug: true // Enable logging
});
`$3
Problem:
SyntaxError: The requested module does not provide an export named 'default'Solutions:
Use one of these import methods:
`javascript
// Method 1: Default import (recommended)
import CdpLiteSdk from 'cdp-lite-sdk';// Method 2: Named import
import { CdpLiteSdk } from 'cdp-lite-sdk';
// Method 3: CommonJS
const CdpLiteSdk = require('cdp-lite-sdk');
`$3
Problem: CORS error in browser console
Solution: Ensure your domain is whitelisted on the API server.
$3
Problem: Events take time to send
Explanation: Events are batched by default for performance.
Solutions:
`javascript
// Reduce batch size
const cdp = new CdpLiteSdk({
apiKey: 'your-api-key',
batchSize: 1 // Send immediately
});// Or manually flush
cdp.track('important_event', {...});
await cdp.flush();
`$3
Problem: Type errors in TypeScript
Solution: Ensure types are imported:
`typescript
import CdpLiteSdk, { CdpConfig } from 'cdp-lite-sdk';const config: CdpConfig = {
apiKey: 'your-api-key'
};
const cdp = new CdpLiteSdk(config);
`---
📝 Event Naming Best Practices
Use
object_action format:`javascript
// ✅ Good
cdp.track('product_viewed');
cdp.track('cart_item_added');
cdp.track('checkout_completed');
cdp.track('user_registered');// ❌ Avoid
cdp.track('viewProduct');
cdp.track('AddItemToCart');
cdp.track('CHECKOUT');
`---
🔒 Privacy & Security
- 🔐 AES-256-CBC Encryption for sensitive user data
- 🔑 HMAC-SHA256 Signatures for request authentication
- 🆔 Anonymous IDs generated automatically
- 📊 Selective Encryption - only sensitive fields are encrypted
- 🔒 HTTPS Only - all data transmitted over secure connections
- 🔑 Secret Key Protection - never expose secret keys
- 🚫 No Plain Text - sensitive data never sent unencrypted
Security Best Practices:
`javascript
// ✅ Use environment variables
const cdp = new CdpLiteSdk({
apiKey: process.env.CDP_API_KEY,
secretKey: process.env.CDP_SECRET_KEY
});// ❌ Never hardcode keys
const cdp = new CdpLiteSdk({
apiKey: 'abc123', // DON'T DO THIS
secretKey: 'secret123'
});
`📖 Full Security Guide: SECURITY.md
---
📄 License
MIT License - see LICENSE file for details
---
🤝 Support
- 📖 Full Documentation
- 🆔 ID Management Guide
- 👤 User Tracking Guide
- 🔒 Security Guide
- 📧 Email: vinv@vega.com.vn
---🎉 Quick Reference
`javascript
// Initialize
const cdp = new CdpLiteSdk({ apiKey: 'key' });// Identify
cdp.identify('user_id', { name: 'John' });
// Track
cdp.track('event_name', { prop: 'value' });
// Page
cdp.page('Page Name');
// Flush
await cdp.flush();
// Reset
cdp.reset();
``---
Made with ❤️ by Your Team