baseerah-sdk-web
v0.1.1
Published
Web SDK for the Unified Analytics & Engagement Platform
Maintainers
Readme
Baseerah Web SDK
Web SDK for the Unified Analytics & Engagement Platform. Event tracking, user identification, and feature flags.
Installation
npm / yarn
npm install baseerah-sdk-web
# or
yarn add baseerah-sdk-webScript Tag
<script src="https://unpkg.com/baseerah-sdk-web/dist/platform.js"></script>Quick Start
Script Tag Usage
<script src="platform.js"></script>
<script>
platform.init('pk_live_your_api_key', {
apiHost: 'https://api.yourplatform.com',
autocapture: true,
});
// Track an event
platform.capture('button_clicked', { button: 'signup' });
</script>Module Usage
import { init, capture, identify } from 'baseerah-sdk-web';
// Initialize the SDK
init('pk_live_your_api_key', {
apiHost: 'https://api.yourplatform.com',
autocapture: true,
});
// Track events
capture('button_clicked', { button: 'signup' });
// Identify users
identify('user_123', { email: '[email protected]', name: 'John' });Configuration Options
platform.init('pk_live_xxx', {
// API host (default: 'https://gateway.baseerah.com')
apiHost: 'https://api.yourplatform.com',
// Enable automatic pageview tracking (default: true)
autocapture: true,
// Storage type: 'localStorage' | 'sessionStorage' | 'memory' (default: 'localStorage')
persistence: 'localStorage',
// Flush interval in milliseconds (default: 5000)
flushInterval: 5000,
// Maximum events per batch (default: 10)
flushBatchSize: 10,
// Maximum retry attempts (default: 3)
maxRetries: 3,
// Enable debug logging (default: false)
debug: false,
});API Reference
Event Tracking
capture(event, properties?)
Track a custom event with optional properties.
platform.capture('purchase_completed', {
product_id: 'SKU123',
price: 99.99,
currency: 'SAR',
});User Identification
identify(distinctId, properties?)
Identify a user and set their properties.
platform.identify('user_123', {
email: '[email protected]',
name: 'Ahmed',
plan: 'premium',
});alias(alias, distinctId?)
Create an alias for a user.
platform.alias('company_123', 'user_123');reset()
Reset the user (call on logout). Creates a new anonymous distinct ID.
platform.reset();setPersonProperties(properties)
Set properties on the current user without changing their ID.
platform.setPersonProperties({
last_login: new Date().toISOString(),
visits: 42,
});Feature Flags
isFeatureEnabled(key, defaultValue?)
Check if a feature flag is enabled.
if (platform.isFeatureEnabled('new_dashboard')) {
// Show new dashboard
}getFeatureFlag(key)
Get the value of a feature flag.
const variant = platform.getFeatureFlag('checkout_experiment');
// Returns: boolean | string | undefinedreloadFeatureFlags()
Reload feature flags from the server.
await platform.reloadFeatureFlags();onFeatureFlags(callback)
Called with current feature flags.
platform.onFeatureFlags((flags) => {
console.log('Feature flags:', flags);
});Utility Methods
getDistinctId()
Get the current user's distinct ID.
const distinctId = platform.getDistinctId();getSessionId()
Get the current session ID.
const sessionId = platform.getSessionId();flush()
Manually flush the event queue.
platform.flush();debug(enabled)
Enable or disable debug logging.
platform.debug(true);Multi-App Setup
If your organization uses multiple apps within a single tenant (e.g., a web storefront and an admin portal), each app is issued its own key pair during creation: a public key (pk_app_*) for client-side use and a secret key (sk_app_*) for server-side use. Initialize the SDK with the app's public key instead of the tenant-level API key. All events captured by the SDK will automatically be scoped to that app.
Initializing with an App Key
import { init, capture } from 'baseerah-sdk-web';
// Use the app-specific public key (pk_app_*), not the tenant key (pk_live_*)
init('pk_app_storefront_abc123', {
apiHost: 'https://api.yourplatform.com',
autocapture: true,
});
// Events are automatically scoped to the "storefront" app
capture('product_viewed', { product_id: 'SKU-42' });Script Tag Usage
<script src="platform.js"></script>
<script>
platform.init('pk_app_admin_xyz789', {
apiHost: 'https://api.yourplatform.com',
});
</script>You can obtain app keys from the dashboard under Settings > Apps, or via the POST /api/apps management API which returns both publicKey and secretKey in the response. The secret key (sk_app_*) is shown only once at creation time -- store it securely for any server-side usage.
Automatic Tracking
When autocapture: true is set (default), the SDK automatically tracks:
- Pageviews: Tracked on initial load and route changes (SPA-compatible)
- Page URL, referrer, and navigation timing
Event Properties
All events automatically include:
| Property | Description |
|----------|-------------|
| $lib | SDK identifier (web) |
| $lib_version | SDK version |
| $current_url | Current page URL |
| $host | Current host |
| $pathname | Current path |
| $referrer | Referring URL |
| $browser | Browser name |
| $browser_version | Browser version |
| $os | Operating system |
| $os_version | OS version |
| $device_type | Device type (Desktop/Mobile/Tablet) |
| $screen_width | Screen width |
| $screen_height | Screen height |
| $viewport_width | Viewport width |
| $viewport_height | Viewport height |
| $session_id | Current session ID |
| $timezone | User's timezone |
Offline Support
Events are queued locally when offline and automatically sent when the connection is restored. The queue persists across page loads using localStorage.
Retry Logic
Failed requests are automatically retried with exponential backoff:
- Retry 1: ~1 second
- Retry 2: ~2 seconds
- Retry 3: ~4 seconds
- Maximum delay: 30 seconds
After max retries, events remain in the queue for later retry.
Bundle Size
- Target: < 15KB gzipped
- UMD:
dist/platform.js - ESM:
dist/platform.esm.js - Types:
dist/platform.d.ts
TypeScript
Full TypeScript support with type definitions included.
import { init, capture, PlatformOptions, CaptureEvent } from 'baseerah-sdk-web';Browser Support
- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
Session Recording
Record user sessions for replay in the dashboard. Recording is lazy-loaded to keep the core bundle small.
import { startRecording, stopRecording } from 'baseerah-sdk-web/recording';
// Start recording (loads rrweb automatically)
startRecording();
// Stop recording
stopRecording();Privacy controls:
maskAllInputs: true(default) — masks all input valuesdata-platform-maskattribute — mask specific elementsdata-platform-blockattribute — completely hide elementsdata-platform-unmaskattribute — override mask for specific elements
Configure in init:
init('pk_xxx', {
recording: true, // auto-start recording
recordingOptions: {
maskAllInputs: true,
blockSelectors: ['.sensitive-data'],
maskSelectors: ['.user-content'],
},
});In-App Messaging
Show modals, banners, and tooltips to users.
import { showInAppMessage } from 'baseerah-sdk-web/messaging';
showInAppMessage({
type: 'modal', // 'modal' | 'banner' | 'tooltip'
title: 'Welcome!',
body: 'Thanks for signing up.',
ctaText: 'Get Started',
ctaUrl: '/onboarding',
});Development
# Install dependencies
npm install
# Build
npm run build
# Watch mode
npm run dev
# Run tests
npm test
# Check bundle size
npm run size
# Type check
npm run typecheckLicense
MIT
