npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

cdp-lite-sdk

v0.1.8

Published

CDP Lite SDK for tracking events and users - Customer Data Platform

Readme

CDP Lite SDK 🚀

Customer Data Platform SDK for tracking events and users. A lightweight, powerful analytics SDK for JavaScript/TypeScript applications.

npm version License: MIT

📋 Table of Contents


  • 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-sdk

Yarn

yarn add cdp-lite-sdk

CDN (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 event
  • properties (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 identifier
  • traits (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_name
  • idcard, old_idcard
  • phone, email
  • gender, dob
  • address, 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 seconds

Disable 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:

  1. Check API key is correct
  2. Enable debug mode: debug: true
  3. Check network tab in DevTools
  4. 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


🎉 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