cap-hydra-web-sdk
v1.1.0
Published
Capillary Hydra WebSDK - JavaScript/TypeScript SDK for web applications
Maintainers
Readme
WebSDK Integration Guide
A comprehensive guide for integrating the Hydra WebSDK into your web application for event tracking, user identification, and analytics.
Basic WebSDK Integration
1. Installation
NPM (recommended):
npm install cap-hydra-web-sdkCDN / Script tag:
<script src="https://cdn.jsdelivr.net/npm/cap-hydra-web-sdk@latest/dist/index.umd.min.js"></script>2. Importing the SDK
ES6 Modules (TypeScript / JavaScript):
import { WebSDK } from 'cap-hydra-web-sdk';CommonJS:
const { WebSDK } = require('cap-hydra-web-sdk');When using the CDN script tag, WebSDK is available as a global on the window object.
3. SDK Initialization
Call WebSDK.initialize() once at application startup. The SDK uses Firebase Remote Config to fetch backend configuration (accountId, baseURL, debugLevel, etc.) automatically — you only need to provide Firebase credentials and the Remote Config key.
import { WebSDK } from 'cap-hydra-web-sdk';
WebSDK.initialize({
firebaseConfig: {
apiKey: 'YOUR_FIREBASE_API_KEY',
authDomain: 'your-app.firebaseapp.com',
databaseURL: 'https://your-app.firebaseio.com',
projectId: 'your-project-id',
storageBucket: 'your-app.appspot.com',
messagingSenderId: '123456789',
appId: 'your-firebase-app-id',
},
remoteConfigKey: 'your_app_config_key',
appVersion: '1.0.0',
});Important: Initialize the SDK at module load time — not inside React
useEffect, AngularngOnInit, or similar async lifecycle hooks. This ensures the SDK instance exists before any component attempts to use it.
4. Basic Event Tracking
// Track a page view (auto-captures URL and title)
WebSDK.pageView();
// Track a custom event
WebSDK.track('page_view', {
page: 'homepage',
});
// Track with detailed properties
WebSDK.track('add_to_cart', {
product_id: 'shoe-123',
product_name: 'Nike Air Max',
quantity: 1,
price: 129.99,
currency: 'USD',
});5. User Identification
When a user logs in, call identify() to link their activity to a known identity:
WebSDK.identify({
identifier: { type: 'email', cuid: '[email protected]' },
actionType: 'USER_REGISTER',
traits: {
firstName: 'John',
lastName: 'Doe',
},
});Supported identifier types: 'email', 'mobile', 'externalId'.
When the user logs out, call reset() to return to anonymous tracking:
WebSDK.reset();React Integration Example
For React applications, wrap the SDK in a service and initialize at module load time:
// services/sdkService.ts
import { WebSDK } from 'cap-hydra-web-sdk';
class SDKService {
initialize() {
WebSDK.initialize({
firebaseConfig: {
/* ... */
},
remoteConfigKey: 'your_app_config_key',
appVersion: '1.0.0',
notifications: {
vapidKey: 'YOUR_VAPID_KEY',
},
});
}
trackEvent(name: string, properties?: Record<string, unknown>) {
WebSDK.track(name, properties);
}
trackPageView() {
WebSDK.pageView();
}
identifyUser(type: 'email' | 'mobile' | 'externalId', cuid: string, traits?: object) {
WebSDK.identify({
identifier: { type, cuid },
actionType: 'USER_REGISTER',
traits,
});
}
getUser() {
return WebSDK.getUser();
}
reset() {
WebSDK.reset();
}
}
export const sdkService = new SDKService();
// Initialize immediately at module load
sdkService.initialize();// App.tsx
import { useEffect } from 'react';
import { sdkService } from './services/sdkService';
function App() {
useEffect(() => {
sdkService.trackPageView();
}, []);
return <Dashboard />;
}Configuration
SDK configuration values like accountId, baseURL, debugLevel, etc. are automatically fetched from Firebase Remote Config. The host application only needs to provide Firebase credentials and the Remote Config key.
Required Fields
| Field | Type | Description |
| ----------------- | ---------------- | ------------------------------------------ |
| firebaseConfig | FirebaseConfig | Firebase project configuration |
| remoteConfigKey | string | Key to fetch SDK config from Remote Config |
Fields
| Field | Type | Default | Description |
| --------------- | -------------------- | ----------------------------------------- | ------------------------------------------------------------ |
| appVersion | string | — | Host application version (populates app_version in events) |
| retryDelays | number[] | [60000, 120000, 240000, 480000, 900000] | Custom retry delays in milliseconds |
| notifications | NotificationConfig | — | Push notification configuration |
Auto-populated Fields (from Remote Config)
The following fields are fetched from Firebase Remote Config. Do not set them manually.
| Field | Required | Default | Description |
| ----------------------- | -------- | --------- | ------------------------------------------------------------ |
| accountId | Yes | — | Organization account identifier |
| baseURL | Yes | — | API base URL for all SDK requests |
| orgId | Yes | — | Organization ID for API authentication |
| brandId | No | — | Brand identifier for namespaced database names |
| applicationId | No | — | Application identifier for namespaced database names |
| source | No | WEBPUSH | Source identifier for visitor profiles |
| channelType | No | web | Communication channel type |
| sessionTimeoutMinutes | No | 30 | Session inactivity timeout in minutes |
| batchSize | No | 50 | Max events per batch request |
| debugLevel | No | NONE | Logging level (NONE / ERROR / WARN / INFO / DEBUG) |
Example Remote Config JSON (stored as the value of your remoteConfigKey in Firebase Console):
{
"accountId": "100458",
"baseURL": "https://api.example.capillarytech.com",
"orgId": "100458",
"brandId": "1",
"applicationId": "2",
"source": "WEBPUSH",
"channelType": "web",
"sessionTimeoutMinutes": 30,
"batchSize": 50,
"debugLevel": "NONE"
}Public API Reference
All 8 public methods are static and accessed via WebSDK.*. All methods (except initialize) internally wait for SDK initialization to complete before executing.
1. initialize(config)
Creates and initializes the SDK singleton. Must be called once before any other method. Safe to call multiple times — subsequent calls return the existing instance.
const sdk = WebSDK.initialize({
firebaseConfig: {
/* ... */
},
remoteConfigKey: 'your_app_config_key',
appVersion: '1.0.0',
});| Parameter | Type | Required | Description |
| --------- | -------------- | -------- | ------------------------ |
| config | WebSDKConfig | Yes | SDK configuration object |
2. track(eventName, properties?)
Tracks a custom behavioral event.
WebSDK.track('button_click', {
button_id: 'checkout',
page: 'cart',
value: 99.99,
});| Parameter | Type | Required | Description |
| ------------ | ------------------------- | -------- | ----------------------- |
| eventName | string | Yes | Name of the event |
| properties | Record<string, unknown> | No | Custom event properties |
3. pageView(options?)
Tracks a page view event. If called with no arguments, automatically captures the current URL and page title.
// Automatic capture
WebSDK.pageView();
// With custom options
WebSDK.pageView({
url: 'https://example.com/products/123',
title: 'Product Detail',
category: 'product',
properties: { productId: 'SKU-123' },
});| Parameter | Type | Required | Description |
| --------- | ----------------- | -------- | ------------------ |
| options | PageViewOptions | No | Page view metadata |
PageViewOptions fields:
| Field | Type | Description |
| ------------ | ------------------------- | --------------------------------------------------------- |
| url | string | Override the current page URL |
| title | string | Override the current page title |
| category | string | Page category (e.g., 'blog', 'product', 'checkout') |
| properties | Record<string, unknown> | Custom properties |
4. identify(params)
Identifies a user (login/signup) or updates user profile attributes. This is the primary method for user identity management.
// User login / signup
WebSDK.identify({
identifier: { type: 'email', cuid: '[email protected]' },
actionType: 'USER_REGISTER',
traits: {
firstName: 'John',
lastName: 'Doe',
gender: 'male',
custom: { plan: 'premium' },
},
});
// User profile update
WebSDK.identify({
identifier: { type: 'mobile', cuid: '+1234567890' },
actionType: 'USER_UPDATE',
traits: {
firstName: 'John',
lastName: 'Smith',
},
});| Parameter | Type | Required | Description |
| --------- | ---------------- | -------- | ------------------- |
| params | IdentifyParams | Yes | Identity parameters |
IdentifyParams fields:
| Field | Type | Required | Description |
| ------------ | -------------------- | -------- | ------------------------------------ |
| identifier | Identifier | Yes | User identifier (type + cuid) |
| actionType | IdentifyActionType | Yes | 'USER_REGISTER' or 'USER_UPDATE' |
| traits | IdentifyTraits | No | User profile attributes |
Identifier.type values: 'email', 'mobile', 'externalId'
IdentifyTraits fields:
| Field | Type | Description |
| ----------- | ------------------------- | ----------------------------------------------- |
| firstName | string | First name |
| lastName | string | Last name |
| gender | string | Gender |
| birthday | string | Birthday |
| city | string | City |
| country | string | Country |
| timezone | string | Timezone |
| custom | Record<string, unknown> | Additional custom attributes merged into events |
5. getUser()
Returns a snapshot of the current user's identity, session, and engagement status. Only available when the user is anonymous — throws an error after identify() has been called, to prevent exposure of identified-user data.
const userInfo = WebSDK.getUser();
console.log(userInfo.visitorId); // "visitor-abc-123"
console.log(userInfo.isAnonymous); // true
console.log(userInfo.sessionNumber); // 1
console.log(userInfo.isFirstSession); // trueReturns: UserInfo
| Field | Type | Description |
| -------------------- | --------------------------------- | ---------------------------------------- |
| visitorId | string | The anonymous visitor ID |
| userId | string \| null | Always null for anonymous users |
| sessionId | string | The current session ID |
| isIdentified | boolean | Always false for anonymous users |
| isAnonymous | boolean | Always true for anonymous users |
| profileTier | 'anonymous' \| 'known' | Always 'anonymous' for anonymous users |
| attributes | Record<string, unknown> \| null | Always null for anonymous users |
| sessionNumber | number | Number of sessions for this visitor |
| isFirstSession | boolean | true when sessionNumber === 1 |
| isReturningVisitor | boolean | true when sessionNumber > 1 |
Throws: Error if the user is identified (i.e., after identify() has been called).
6. enableSDK()
Re-enables event tracking after it was disabled. Pending events in the queue are processed.
WebSDK.enableSDK();7. disableSDK()
Disables event tracking. New events are dropped. Existing queued events are preserved in IndexedDB and will be sent when the SDK is re-enabled.
WebSDK.disableSDK();8. reset()
Signs out the current user and returns the SDK to anonymous tracking mode.
WebSDK.reset();Push Notifications
To enable push notifications, add the notifications config to initialize():
WebSDK.initialize({
firebaseConfig: {
/* ... */
},
remoteConfigKey: 'your_app_config_key',
notifications: {
vapidKey: 'YOUR_VAPID_KEY',
serviceWorkerPath: '/firebase-messaging-sw.js',
},
});Service Worker Setup:
- Obtain the
firebase-messaging-sw.jsservice worker template from the Capillary team and place it in your project'spublic/directory. Update the Firebase config inside the file with your actual credentials. - Set
serviceWorkerPathto the URL path where the file is accessible from the browser.
serviceWorkerPath depends on where your app is served from:
| Scenario | serviceWorkerPath value |
| ---------------------------------------------- | ------------------------------------- |
| App at root (https://example.com/) | /firebase-messaging-sw.js (default) |
| App at subpath (https://example.com/my-app/) | /my-app/firebase-messaging-sw.js |
If not provided, it defaults to /firebase-messaging-sw.js.
Minimum Browser Requirements
| Browser | Minimum Version | Notes | | ------- | --------------- | ----------------------------------------------------- | | Chrome | 49+ | Full support | | Firefox | 52+ (ESR) | Full support | | Safari | 10+ | Service Worker requires 11.1+ | | Edge | 79+ (Chromium) | Full support | | IE | 11 | Limited: no Service Worker, no Push API, no Web Locks |
