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

vc-cdp-web-sdk

v0.2.1

Published

CDP SDK for Web - Customer Data Platform tracking for browsers and SSR

Readme

vc-cdp-web-sdk

CDP SDK cho Web — tracking events va user profiles cho he thong Customer Data Platform noi bo VietCredit.

Ho tro Browser (Vanilla JS, React, Vue, Angular, ...) va SSR (Next.js, Nuxt.js, ...).


Muc luc

Thay doi tu 0.2.0: SDK khong con goi cac API /v1/profiles/* (track/update/get profile) — cac API nay gio chi goi tu backend. SDK chi con goi POST /v2/events/track va POST /v2/events/batch, kem header Authorization: Bearer <accessToken>. Cac ham updateProfile, getProfile, add_*, setUserAttributes, setConsents, setScores, setProducts, setMetadata, getUserAttribute va config enableEncryption da bi bo. SDK cung khong con giu dinh danh user: da bo identifyUser/identify, setProfileId, getProfileId; event khong con user_id; profile_id cua event duoc SDK tu lay tu pid trong access token luc gui (ingest bat 2 gia tri phai khop); khong co token -> event khong co profile_id.


Cai dat

npm install vc-cdp-web-sdk

CDN (khong can build tool)

<!-- Load SDK tu CDN -->
<script src="https://unpkg.com/vc-cdp-web-sdk/dist/vc-cdp-web-sdk.umd.min.js"></script>
const { CdpWebSdk } = VcCdpWebSdk;

Khoi tao

import { CdpWebSdk } from 'vc-cdp-web-sdk';

const cdp = new CdpWebSdk({
  apiKey:     'YOUR_API_KEY',
  secretKey:  'YOUR_SECRET_KEY',
  source:     'DOP',
  serviceName: 'VC_APP',
  accessToken: 'YOUR_ACCESS_TOKEN', // gui kem header Authorization: Bearer <token>

  // Tuy chon
  baseUrl:           'https://ingestlog.vietcredit.com.vn', // mac dinh: staging
  isTest:            false,
  debug:             false,
  batchSize:         10,       // gui batch khi du n events
  batchInterval:     5000,     // hoac sau n ms
  autoTrackPageView: false,    // tu track page_view khi URL thay doi (SPA)
  deviceId:          'custom-device-id', // tuy chon: set device_id tuy chinh
});

Luu y: Khoi tao la synchronous — khong can await. SDK dung localStorage va sessionStorage nen hoat dong ngay lap tuc.

Cau hinh day du

| Tham so | Kieu | Mac dinh | Mo ta | |---------|------|----------|-------| | apiKey | string | — | Bat buoc. API Key do CDP cap | | secretKey | string | — | Bat buoc. Secret Key de ky HMAC | | source | string | — | Bat buoc. Kenh tich hop (khai bao voi CDP truoc) | | serviceName | string | — | Bat buoc. VC_APP, DOP, LOS, LMS | | accessToken | string | — | Token gui kem header Authorization: Bearer <token> cho /v2/events/*. Doi sau bang setAccessToken() | | baseUrl | string | Staging URL | URL API CDP (khong co /v2) | | isTest | boolean | false | Danh dau moi truong test | | debug | boolean | false | In log ra console | | batchSize | number | 10 | So events toi da trong 1 batch | | batchInterval | number | 5000 | Thoi gian (ms) giua cac lan flush tu dong | | autoTrackPageView | boolean | false | Tu track page view khi URL thay doi (SPA) | | deviceId | string | Auto UUID | Device ID tuy chinh. Neu khong set, SDK tu sinh UUID va luu vao localStorage |

Moi truong

| Moi truong | baseUrl | |------------|---------| | Staging | https://stg-ingestlog.vietcredit.com.vn | | Production | https://ingestlog.vietcredit.com.vn |

API SDK goi

| API | Khi nao | |-----|---------| | POST /v2/events/track | batchSize <= 1 — gui tung event | | POST /v2/events/batch | batchSize > 1 — gui theo lo |

Header: X-Api-Key, X-Source, X-Timestamp, X-Signatures, X-Trace-Id, isTest, Authorization: Bearer <accessToken> (khi co token).


Luong hoat dong

Trang load
  +-> new CdpWebSdk(config)
        |  - device_id: dung config.deviceId neu co, khong thi load/tao tu localStorage
        |  - Load/tao anonymous_id -> localStorage (persist mai)
        |  - Load/tao session_id   -> sessionStorage (per tab)
        |  - Parse UTM params tu URL tu dong
        |
        +- User CHUA login
        |     +-> cdp.track() / cdp.page()
        |           gan anonymous_id + device_id + session_id
        |
        +- User login (backend tao/cap nhat profile qua /v1/profiles/*, tra ve token)
              +-> cdp.setAccessToken(token)
                    +-> cdp.track() gui kem Authorization: Bearer <token>
                        (backend xac dinh user qua token)

Storage scope:

| Key | localStorage | sessionStorage | |-----|-------------|----------------| | device_id | Vinh vien (hoac tu config.deviceId) | - | | anonymous_id | Vinh vien | - | | session_id | - | Per tab (mat khi dong tab) |


Access token & session

Profile (/v1/profiles/*) chi goi tu backend, va SDK khong giu user_id / profile_id: backend xac dinh user qua access token. Sau khi dang nhap, chi can goi setAccessToken().

profile_id cua event duoc SDK tu lay tu pid trong access token luc gui (ingest bat 2 gia tri phai khop); khong co token -> event khong co profile_id. Gan luc gui nen event tao truoc khi login van khop voi token trong header.

setAccessToken — Authorization Bearer

Cap nhat token dung cho header Authorization: Bearer <token> khi goi /v2/events/*. Goi lai moi khi refresh token. Truyen null de bo header.

cdp.setAccessToken(newToken);

Campaign / Platform

// SDK tu parse UTM tu URL. Override thu cong:
cdp.setCampaign({
  utm_source:   'facebook',
  utm_medium:   'cpc',
  utm_campaign: 'summer_loan_2025',
  utm_term:     'vay_tieu_dung',
  utm_content:  'banner_top',
});

cdp.setPlatform({ app_version: '2.1.0' });

getUserIdentities

const ids = cdp.getUserIdentities();
// {
//   anonymous_id: 'uuid-...',
//   device_id:    'uuid-...',
//   session_id:   'uuid-...',
// }

cdp.getDeviceId();               // persistent per browser
cdp.getSessionId();              // per tab (sessionStorage)

destroy_session — Dang xuat

Flush cac event con trong queue, roi reset session. Khong goi API profile.

await cdp.destroy_session();
cdp.setAccessToken(null); // neu token gan voi user
// hoac alias:
await cdp.reset();

| Field | Hanh dong | |-------|-----------| | campaign | Xoa | | anonymous_id | Tao moi, luu localStorage | | session_id | Tao moi, luu sessionStorage | | device_id | Giu nguyen | | accessToken | Giu nguyen (tu goi setAccessToken(null) neu can) |


Event Tracking

track — Custom event

cdp.track(eventName, properties?)
cdp.track('button_click');

cdp.track('loan_viewed', {
  loan_id: 'LOAN_001',
  amount:  50000000,
  term:    24,
  type:    'consumer',
});

cdp.track('form_submitted', {
  form:    'loan_application',
  success: true,
});

page — Page view

Track luot xem trang. Tu dong ghi url, path, referrer, title.

cdp.page(pageName?, properties?)
cdp.page();                        // tu dong capture url/referrer/title
cdp.page('Trang chu');
cdp.page('Chi tiet san pham', {
  product_code: 'LOAN_CONSUMER',
  campaign:     'SUMMER_2025',
});

screen — Screen view (SPA)

cdp.screen('DashboardScreen');
cdp.screen('LoanDetailScreen', { loan_id: 'LOAN_001' });

Auto Page View (SPA)

Bat autoTrackPageView: true de SDK tu track page_view moi khi URL thay doi — khong can goi cdp.page() thu cong.

SDK hook vao:

  • history.pushState (React Router, Vue Router, Next.js)
  • history.replaceState
  • window.popstate (trinh duyet back/forward)

Luu y: Khi dung SSR (Next.js, Nuxt.js), chi init SDK o phia client de tranh loi window is not defined.


Batch Processing

Events khong gui ngay tung cai ma duoc gom vao queue roi flush theo dieu kien:

| Dieu kien | Mo ta | |-----------|-------| | batchSize dat nguong | Mac dinh 10 events | | batchInterval timeout | Mac dinh 5000 ms | | Tab dong (beforeunload) | Flush dong bo | | Tab an (visibilitychange) | Flush khi chuyen sang background |

const cdp = new CdpWebSdk({
  batchSize:     20,    // gui khi co 20 events
  batchInterval: 3000,  // hoac sau 3 giay
});

flush — Gui ngay

await cdp.flush();
document.querySelector('#submit-btn').addEventListener('click', async () => {
  cdp.track('form_submitted', { form: 'loan_application' });
  await cdp.flush(); // dam bao event duoc gui
  window.location.href = '/thank-you';
});

destroy — Don dep SDK

cdp.destroy();

Xoa batch interval timer, xoa history listener, flush queue con lai. Khong xoa user data.


Bao mat

HMAC-SHA256 Signature

Moi request den CDP API deu duoc ky tu dong.

Headers duoc gui:

X-Api-Key:    <apiKey>
X-Source:     <source>
X-Timestamp:  <unix_timestamp_ms>
X-Signatures: <base64_signature>
X-Trace-Id:   <uuid>
Content-Type: application/json
isTest:       false

Cong thuc:

signature = Base64( HMAC-SHA256(secretKey, message) )
message   = source + "|" + timestamp + "|" + JSON(payload)

| Thanh phan | Mo ta | |------------|-------| | secretKey | Secret Key duoc CDP cap | | source | Kenh tich hop (vi du: DOP) | | timestamp | Unix timestamp tinh bang milliseconds (Date.now()) | | payload | Body JSON string (GET request: chuoi rong) |


Authorization Bearer

Moi request /v2/events/track va /v2/events/batch gui kem:

Authorization: Bearer <accessToken>

accessToken truyen vao khi khoi tao (config.accessToken) va cap nhat bang cdp.setAccessToken() khi refresh. Neu chua co token, SDK khong gui header nay.


Best Practices

  • Dung key khac nhau cho moi moi truong (dev / staging / production).
  • Rotate key dinh ky theo chinh sach CDP team.
  • Bat debug: false tren production build.
  • Luon dung https:// cho baseUrl.
  • Khong log accessToken; goi setAccessToken() ngay khi refresh token.
// Development
const cdp = new CdpWebSdk({ ...config, debug: true, isTest: true });

// Production
const cdp = new CdpWebSdk({ ...config, debug: false });

Tich hop Framework

React / Next.js

React (Create React App / Vite)

// src/lib/cdp.ts
import { CdpWebSdk } from 'vc-cdp-web-sdk';

export const cdp = new CdpWebSdk({
  apiKey:     process.env.REACT_APP_CDP_API_KEY!,
  secretKey:  process.env.REACT_APP_CDP_SECRET_KEY!,
  source:     'DOP',
  serviceName: 'VC_APP',
  baseUrl:    process.env.REACT_APP_CDP_BASE_URL,
  debug:      process.env.NODE_ENV === 'development',
  autoTrackPageView: true,
});
// src/hooks/useAuth.ts
import { cdp } from '../lib/cdp';

export function useLogin() {
  const login = async (phone: string, password: string) => {
    // Backend tu goi /v1/profiles/* va tra ve accessToken (chua dinh danh user)
    const user = await authApi.login(phone, password);
    cdp.setAccessToken(user.accessToken);
    return user;
  };

  const logout = async () => {
    await authApi.logout();
    await cdp.destroy_session();
  };

  return { login, logout };
}
# .env.local
REACT_APP_CDP_API_KEY=YOUR_API_KEY
REACT_APP_CDP_SECRET_KEY=YOUR_SECRET_KEY
REACT_APP_CDP_BASE_URL=https://stg-ingestlog.vietcredit.com.vn

Next.js (App Router)

SDK phai chay o client side vi can localStorage va window.

// src/lib/cdp.ts
'use client';

import { CdpWebSdk } from 'vc-cdp-web-sdk';

let _cdp: CdpWebSdk | null = null;

export function getCdp(): CdpWebSdk {
  if (typeof window === 'undefined') {
    return { track: () => {}, page: () => {}, setAccessToken: () => {} } as any;
  }
  if (!_cdp) {
    _cdp = new CdpWebSdk({
      apiKey:     process.env.NEXT_PUBLIC_CDP_API_KEY!,
      secretKey:  process.env.NEXT_PUBLIC_CDP_SECRET_KEY!,
      source:     'DOP',
      serviceName: 'VC_APP',
      baseUrl:    process.env.NEXT_PUBLIC_CDP_BASE_URL,
      debug:      process.env.NODE_ENV === 'development',
      autoTrackPageView: true,
    });
  }
  return _cdp;
}
// src/components/CdpProvider.tsx
'use client';

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { getCdp } from '../lib/cdp';

export function CdpProvider({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();

  useEffect(() => {
    getCdp().page(document.title);
  }, [pathname]);

  return children;
}
// src/app/layout.tsx
import { CdpProvider } from '../components/CdpProvider';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <CdpProvider>{children}</CdpProvider>
  );
}
// src/hooks/useCdp.ts
'use client';
import { getCdp } from '../lib/cdp';
export function useCdp() { return getCdp(); }
# .env.local
NEXT_PUBLIC_CDP_API_KEY=YOUR_API_KEY
NEXT_PUBLIC_CDP_SECRET_KEY=YOUR_SECRET_KEY
NEXT_PUBLIC_CDP_BASE_URL=https://stg-ingestlog.vietcredit.com.vn

Vue / Nuxt.js

Vue 3 (Vite / Vue CLI)

// src/plugins/cdp.ts
import { App } from 'vue';
import { CdpWebSdk } from 'vc-cdp-web-sdk';

export const cdp = new CdpWebSdk({
  apiKey:     import.meta.env.VITE_CDP_API_KEY,
  secretKey:  import.meta.env.VITE_CDP_SECRET_KEY,
  source:     'DOP',
  serviceName: 'VC_APP',
  baseUrl:    import.meta.env.VITE_CDP_BASE_URL,
  debug:      import.meta.env.DEV,
  autoTrackPageView: true,
});

export const CdpPlugin = {
  install(app: App) {
    app.config.globalProperties.$cdp = cdp;
    app.provide('cdp', cdp);
  },
};
// src/main.ts
import { createApp }  from 'vue';
import App            from './App.vue';
import { CdpPlugin }  from './plugins/cdp';

createApp(App).use(CdpPlugin).mount('#app');
// src/composables/useCdp.ts
import { inject } from 'vue';
import type { CdpWebSdk } from 'vc-cdp-web-sdk';

export function useCdp(): CdpWebSdk {
  return inject('cdp') as CdpWebSdk;
}
// src/router/index.ts — track page view qua Vue Router
router.afterEach((to) => {
  cdp.page(String(to.name ?? to.path));
});
# .env.local
VITE_CDP_API_KEY=YOUR_API_KEY
VITE_CDP_SECRET_KEY=YOUR_SECRET_KEY
VITE_CDP_BASE_URL=https://stg-ingestlog.vietcredit.com.vn

Nuxt.js 3

// plugins/cdp.client.ts  (file .client.ts chi chay o browser)
import { CdpWebSdk } from 'vc-cdp-web-sdk';

export default defineNuxtPlugin(() => {
  const config = useRuntimeConfig();

  const cdp = new CdpWebSdk({
    apiKey:     config.public.cdpApiKey,
    secretKey:  config.public.cdpSecretKey,
    source:     'DOP',
    serviceName: 'VC_APP',
    baseUrl:    config.public.cdpBaseUrl,
    debug:      process.env.NODE_ENV === 'development',
  });

  const router = useRouter();
  router.afterEach((to) => {
    cdp.page(String(to.name ?? to.path));
  });

  return { provide: { cdp } };
});
// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      cdpApiKey:    process.env.NUXT_PUBLIC_CDP_API_KEY,
      cdpSecretKey: process.env.NUXT_PUBLIC_CDP_SECRET_KEY,
      cdpBaseUrl:   process.env.NUXT_PUBLIC_CDP_BASE_URL,
    },
  },
});
# .env
NUXT_PUBLIC_CDP_API_KEY=YOUR_API_KEY
NUXT_PUBLIC_CDP_SECRET_KEY=YOUR_SECRET_KEY
NUXT_PUBLIC_CDP_BASE_URL=https://stg-ingestlog.vietcredit.com.vn

Vanilla JS / CDN

Script tag

Them SDK vao trang web bang the script:

<!-- Load SDK -->
<script src="https://unpkg.com/vc-cdp-web-sdk/dist/vc-cdp-web-sdk.umd.min.js"></script>

Sau do khoi tao va su dung:

var CdpWebSdk = VcCdpWebSdk.CdpWebSdk;

var cdp = new CdpWebSdk({
  apiKey:     'YOUR_API_KEY',
  secretKey:  'YOUR_SECRET_KEY',
  source:     'DOP',
  serviceName: 'VC_APP',
  baseUrl:    'https://ingestlog.vietcredit.com.vn',
});

// Track page view
cdp.page(document.title);

// Track su kien
document.getElementById('apply-btn').addEventListener('click', function() {
  cdp.track('apply_clicked', { product_code: this.dataset.product });
});

// Dang nhap (backend xac dinh user qua token)
cdp.setAccessToken(accessToken);

// Dang xuat
cdp.destroy_session();

Multi-page Website (MPA)

Them vao base template hoac moi trang:

<!-- Load SDK -->
<script src="https://unpkg.com/vc-cdp-web-sdk/dist/vc-cdp-web-sdk.umd.min.js"></script>
window.cdp = new VcCdpWebSdk.CdpWebSdk({
  apiKey:     'YOUR_API_KEY',
  secretKey:  'YOUR_SECRET_KEY',
  source:     'DOP',
  serviceName: 'VC_APP',
  baseUrl:    'https://ingestlog.vietcredit.com.vn',
});
window.cdp.page(document.title);

SDK nhan ra cung user qua device_id (localStorage) du navigate giua cac trang.

ES Modules

// src/analytics.js
import { CdpWebSdk } from 'vc-cdp-web-sdk';

const cdp = new CdpWebSdk({
  apiKey:     process.env.CDP_API_KEY,
  secretKey:  process.env.CDP_SECRET_KEY,
  source:     'DOP',
  serviceName: 'VC_APP',
});

export default cdp;

API Reference

Constructor

new CdpWebSdk(config: CdpWebConfig)

interface CdpWebConfig {
  apiKey:             string;
  secretKey:          string;
  source:             string;
  serviceName:        string;
  accessToken?:       string;   // Authorization: Bearer <token>
  baseUrl?:           string;
  isTest?:            boolean;
  debug?:             boolean;
  batchSize?:         number;
  batchInterval?:     number;
  autoTrackPageView?: boolean;
  deviceId?:          string;
}

Auth / Identity Methods

setAccessToken(token: string | null): this
setCampaign(campaign: CampaignInfo): this
setPlatform(info: PlatformInfo): this

Event Methods

track(eventName: string, properties?: Record<string, unknown>): void
page(pageName?: string, properties?: Record<string, unknown>): void
screen(screenName: string, properties?: Record<string, unknown>): void
async flush(): Promise<void>

Session and Identity Methods

getUserIdentities(): UserIdentities
getDeviceId(): string
getSessionId(): string
async destroy_session(): Promise<this>
async reset(): Promise<this>   // alias
async destroy(): Promise<void> // cleanup timers + flush

Types

interface UserIdentities {
  anonymous_id: string;
  device_id:    string;
  session_id:   string;
}