cdp-lite-sdk
v0.1.8
Published
CDP Lite SDK for tracking events and users - Customer Data Platform
Maintainers
Readme
CDP Lite SDK 🚀
Customer Data Platform SDK for tracking events and users. A lightweight, powerful analytics SDK for JavaScript/TypeScript applications.
📋 Table of Contents
- Features
- Installation
- Quick Start
- Configuration
- Security Features
- 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
NPM
npm install cdp-lite-sdkYarn
yarn add cdp-lite-sdkCDN (Browser)
<script src="https://cdn.jsdelivr.net/npm/cdp-lite-sdk/dist/cdp-lite-sdk.min.js"></script>ES6 Import (Recommended)
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: '[email protected]',
phone: '0901234567'
});
// Track event (auto-signed with HMAC)
cdp.track('button_clicked', {
button_name: 'Sign Up',
page: 'Landing'
});CommonJS (Node.js)
const CdpLiteSdk = require('cdp-lite-sdk');
const cdp = new CdpLiteSdk({
apiKey: 'your-api-key',
source: 'BackendService'
});Browser (Script Tag)
<script src="path/to/cdp-lite-sdk.min.js"></script>
<script>
const cdp = new CdpLiteSdk({
apiKey: 'your-api-key',
source: 'WebApp'
});
cdp.track('page_view', { page: 'Home' });
</script>Configuration Options
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)
});Example Configurations
Development
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
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
});Automatic Data Encryption
SDK automatically encrypts sensitive user data using AES-256-CBC before sending:
// Sensitive data is automatically encrypted
cdp.identify('user_123', {
email: '[email protected]', // Encrypted
phone: '0901234567', // Encrypted
idcard: '001234567890', // Encrypted
// Other fields are not encrypted
city: 'Hanoi',
age: 30
});Request Signing
All API requests are signed with HMAC-SHA256 for authentication:
X-Signatures = Base64(HMAC-SHA256(X-Source + "|" + X-Timestamp + "|" + Payload))Setup Security
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.
1. Track Events
Track custom events with properties.
cdp.track(eventName, properties, options);Parameters:
eventName(string) - Name of the eventproperties(object) - Event properties (optional)options(object) - Additional options (optional)
Example:
// 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'
}
});2. Identify Users
Identify users and set their attributes.
cdp.identify(userId, traits);Parameters:
userId(string) - Unique user identifiertraits(object) - User attributes (optional)
Example:
cdp.identify('user_123', {
// Sensitive fields (auto-encrypted)
full_name: 'Nguyen Van A',
first_name: 'A',
last_name: 'Nguyen Van',
email: '[email protected]',
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
3. Page Views
Track page views (for web applications).
cdp.page(pageName, properties);Example:
cdp.page('Home', {
url: window.location.href,
title: document.title,
referrer: document.referrer
});
cdp.page('Product Details', {
product_id: 'PROD123',
category: 'Electronics'
});4. Screen Views
Track screen views (for mobile applications).
cdp.screen(screenName, properties);Example:
cdp.screen('Home Screen', {
tab: 'featured'
});
cdp.screen('Product Detail', {
product_id: 'PROD123'
});5. Update User Attributes
Update user attributes without re-identifying.
cdp.setUserAttributes(traits);Example:
cdp.setUserAttributes({
subscription: 'premium',
last_login: new Date().toISOString(),
total_purchases: 5
});6. Set Device Info
Manually set device information.
cdp.setDeviceInfo(deviceInfo);Example:
cdp.setDeviceInfo({
platform: 'ios',
brand: 'Apple',
model: 'iPhone 14 Pro',
app_version: '2.1.0',
os_version: '16.3'
});7. Flush Events
Manually send all queued events immediately.
await cdp.flush();Example:
// Add multiple events
cdp.track('event_1');
cdp.track('event_2');
cdp.track('event_3');
// Send all immediately
await cdp.flush();8. Reset User
Clear user data (useful for logout).
cdp.reset();Example:
function handleLogout() {
cdp.reset();
// Redirect to login page
}9. Cleanup
Clean up resources when done.
cdp.destroy();Batch Processing
SDK automatically batches events for efficiency.
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 secondsDisable Batching
Send events immediately:
const cdp = new CdpLiteSdk({
apiKey: 'your-api-key',
batchSize: 1 // Send immediately
});Error Handling
try {
await cdp.track('event_name', { data: 'value' });
console.log('Event tracked successfully');
} catch (error) {
console.error('Failed to track event:', error);
}Custom Context
cdp.track('checkout', {
total: 299.99
}, {
context: {
ip: '192.168.1.1',
locale: 'vi_VN',
timezone: 'Asia/Ho_Chi_Minh',
user_agent: navigator.userAgent
}
});Setup Analytics Context
// 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;Custom Hook
// 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 };
}Usage in Components
// 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 (
<div>
<h1>{product.name}</h1>
<button onClick={handleAddToCart}>Add to Cart</button>
</div>
);
}Auto Page Tracking
// 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 <YourApp />;
}Full TypeScript support with type definitions.
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: '[email protected]',
age: 30
};
cdp.identify('user_123', userTraits);
const eventProps: EventProperties = {
product_id: '123',
price: 99.99,
currency: 'USD'
};
cdp.track('purchase', eventProps);Constructor
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)Methods
| Method | Parameters | Return | Description |
|--------|-----------|--------|-------------|
| track() | eventName, properties?, options? | Promise<any> \| void | Track an event |
| identify() | userId, traits? | Promise<any> \| void | Identify a user |
| page() | pageName, properties? | Promise<any> \| void | Track page view |
| screen() | screenName, properties? | Promise<any> \| void | Track screen view |
| setUserAttributes() | traits | Promise<any> \| void | Update user attrs |
| setDeviceInfo() | deviceInfo | void | Set device info |
| flush() | - | Promise<any> | Flush event queue |
| reset() | - | void | Reset user data |
| destroy() | - | void | Cleanup resources |
E-commerce Tracking
// 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'
});Loan Application Flow
// 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'
});User Authentication
// Registration
cdp.track('user_registered', {
method: 'email',
source: 'organic'
});
cdp.identify('user_123', {
name: 'John Doe',
email: '[email protected]',
created_at: new Date().toISOString()
});
// Login
cdp.track('user_logged_in', {
method: 'email'
});
// Logout
cdp.track('user_logged_out');
cdp.reset();Form Tracking
// 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
});Events Not Sending
Problem: Events are not being tracked
Solutions:
- Check API key is correct
- Enable debug mode:
debug: true - Check network tab in DevTools
- Verify baseUrl is correct
const cdp = new CdpLiteSdk({
apiKey: 'your-api-key',
debug: true // Enable logging
});Import Errors
Problem: SyntaxError: The requested module does not provide an export named 'default'
Solutions:
Use one of these import methods:
// 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');CORS Issues
Problem: CORS error in browser console
Solution: Ensure your domain is whitelisted on the API server.
Events Delayed
Problem: Events take time to send
Explanation: Events are batched by default for performance.
Solutions:
// 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();TypeScript Errors
Problem: Type errors in TypeScript
Solution: Ensure types are imported:
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:
// ✅ 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:
// ✅ 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
- 📧 Email: [email protected]
🎉 Quick Reference
// 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
