API Reference
Complete reference for all PRIV SDK methods including initialization, tracking, identity, consent, and lifecycle methods.
API Reference
Complete reference for all SDK methods.
Initialization
priv.init(config)
Initialize the SDK with your configuration. Must be called before any other methods.
import { priv } from '@priv/sdk';
priv.init({
apiKey: 'pk_your_api_key',
endpoint: 'https://api.privlabs.io',
debug: true,
});Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
config.apiKey | string | Yes | Your PRIV API key |
config.endpoint | string | Yes | Analytics endpoint URL |
config.debug | boolean | No | Enable debug logging |
config.flushInterval | number | No | Flush interval in ms (default: 5000) |
config.flushAt | number | No | Events before auto-flush (default: 10) |
config.autoTrackPageViews | boolean | No | Auto-track pages (default: true) |
config.autoTrackClicks | boolean | No | Auto-track clicks (default: false) |
config.autoTrackScroll | boolean | No | Auto-track scroll (default: false) |
Returns: void
See Configuration for full details.
Tracking Methods
priv.track(event, properties?)
Track a custom event with optional properties.
// Basic tracking
priv.track('button_click');
// With properties
priv.track('purchase', {
product_id: 'prod_123',
price: 99.99,
currency: 'USD',
quantity: 1,
});
// Track form submission
priv.track('form_submitted', {
form_id: 'signup',
fields_filled: 5,
time_spent: 30,
});Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
event | string | Yes | Event name (e.g., 'button_click') |
properties | EventProperties | No | Additional event data |
Properties Type:
type EventProperties = Record<string, string | number | boolean | null | undefined>;Returns: void
Best Practices:
- Use snake_case for event names
- Keep property values simple (strings, numbers, booleans)
- Use consistent naming across your app
priv.page(name?, properties?)
Track a page view with optional name and properties.
// Auto-capture page details
priv.page();
// Named page
priv.page('Dashboard');
// With properties
priv.page('Product Page', {
product_id: 'prod_123',
category: 'electronics',
});Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name | string | No | Page name (defaults to document title) |
properties | EventProperties | No | Additional page data |
Auto-captured Properties:
The SDK automatically captures:
url- Full page URLpath- URL pathnamereferrer- Document referrertitle- Document title
Returns: void
Identity Methods
priv.identify(userId, traits?)
Identify a user and associate them with their events.
// Basic identification
priv.identify('user_123');
// With traits
priv.identify('user_123', {
email: 'user@example.com',
name: 'Alex Rivera',
plan: 'pro',
company: 'Acme Inc',
created_at: '2026-01-15',
});Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
userId | string | Yes | Unique user identifier |
traits | UserTraits | No | User attributes |
Traits Type:
type UserTraits = Record<string, string | number | boolean | null | undefined>;Returns: void
Important: Call identify() after login and before tracking events to ensure all events are associated with the user.
priv.reset()
Clear the current user identity. Call this on logout.
// On user logout
function handleLogout() {
// Clear session
authService.logout();
// Reset analytics identity
priv.reset();
}Returns: void
After calling reset():
- User ID is cleared
- A new anonymous ID is generated
- New session is started
Consent Methods
priv.setConsent(granted)
Set the user's GDPR consent status. Tracking only occurs when consent is granted.
// After user accepts cookies
priv.setConsent(true);
// After user rejects tracking
priv.setConsent(false);Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
granted | boolean | Yes | Whether consent is granted |
Returns: void
GDPR Compliance:
The SDK is designed for GDPR compliance:
- Initialize the SDK (no tracking yet)
- Show consent banner to user
- Call
setConsent(true)when user accepts - Tracking begins
// Initialize SDK (no tracking yet)
priv.init({ apiKey: 'pk_xxx', endpoint: '...' });
// Show your consent banner...
// When user accepts:
onConsentAccepted(() => {
priv.setConsent(true);
priv.track('consent_granted');
});
// When user rejects:
onConsentRejected(() => {
priv.setConsent(false);
});priv.isTracking()
Check if tracking is currently active.
if (priv.isTracking()) {
console.log('User has consented, tracking is active');
} else {
console.log('No consent or SDK not initialized');
}Returns: boolean
Returns true if:
- SDK is initialized
- Consent has been granted via
setConsent(true)
Utility Methods
priv.getAnonId()
Get the anonymous ID for the current user/device.
const anonymousId = priv.getAnonId();
console.log('Anonymous ID:', anonymousId);
// Output: "anon_a7b8c9d0e1f2..."Returns: string
The anonymous ID:
- Is generated on first SDK initialization
- Persists across page loads (stored in localStorage)
- Is included with all events
- Allows event correlation before user identification
priv.shutdown()
Shutdown the SDK and flush any pending events.
// Before page unload or app close
priv.shutdown();Returns: void
Use this:
- Before page unload to ensure events are sent
- When unmounting your app
- For cleanup in single-page applications
// React example
useEffect(() => {
priv.init({ ... });
return () => {
priv.shutdown();
};
}, []);Advanced Utility Methods
These methods are available for advanced use cases like debugging and testing.
getQueueSize()
Get the number of events currently queued.
import { getQueueSize } from '@priv/sdk';
const pending = getQueueSize();
console.log(`${pending} events pending`);Returns: number
Useful for:
- Debugging event batching
- Monitoring queue health
- Testing event tracking
forceFlush()
Force an immediate flush of the event queue.
import { forceFlush } from '@priv/sdk';
// Force flush and wait for completion
const success = await forceFlush();
if (success) {
console.log('Events sent successfully');
} else {
console.log('Flush failed or queue was empty');
}Returns: Promise<boolean>
Useful for:
- Testing scenarios
- Ensuring events are sent before navigation
- Critical event delivery
Note: Normally you don't need to call this - the SDK automatically flushes based on flushInterval (default 5s) and flushAt (default 10 events).
Auto-Tracked Events
When auto-tracking is enabled, the SDK automatically tracks these events:
page_view (auto)
Tracked automatically when autoTrackPageViews: true (default).
Triggered on:
- Initial page load
- SPA navigation (
history.pushState,history.replaceState) - Browser back/forward navigation (
popstate)
click (auto)
Tracked automatically when autoTrackClicks: true.
Tracks clicks on interactive elements: <a>, <button>, <input>, <select>, <textarea>, or any element with data-track attribute.
Auto-captured Properties:
{
tagName: 'button',
elementId: 'signup-btn', // if element has id
className: 'btn primary', // first 3 classes
href: 'https://...', // for links
linkText: 'Click here', // for links
buttonText: 'Sign Up', // for buttons
buttonType: 'submit', // for buttons
inputType: 'text', // for inputs
inputName: 'email', // for inputs
}Custom Tracking Attributes:
Add data-track-* attributes to capture custom properties:
<button data-track data-track-category="cta" data-track-label="hero">
Sign Up
</button>scroll_depth (auto)
Tracked automatically when autoTrackScroll: true.
Reports maximum scroll depth percentage every 30 seconds and on page unload.
Properties:
{
maxDepth: 75, // 0-100 percentage
url: 'https://...',
path: '/pricing',
}TypeScript Types
Import types for full type safety:
import type {
PrivConfig,
EventProperties,
UserTraits,
BaseEvent,
TrackEvent,
IdentifyEvent,
PageEvent,
PrivEvent,
ConsentState,
} from '@priv/sdk';Type Definitions
/** SDK configuration options */
interface PrivConfig {
apiKey: string;
endpoint: string;
debug?: boolean;
flushInterval?: number;
flushAt?: number;
autoTrackPageViews?: boolean;
autoTrackClicks?: boolean;
autoTrackScroll?: boolean;
}
/** Event properties - flexible key-value pairs */
type EventProperties = Record<string, string | number | boolean | null | undefined>;
/** User traits for identification */
type UserTraits = Record<string, string | number | boolean | null | undefined>;
/** Base event structure - all events inherit these fields */
interface BaseEvent {
/** Unique event ID */
id: string;
/** Event timestamp (ISO 8601) */
timestamp: string;
/** Anonymous ID for unidentified users */
anonymousId: string;
/** User ID if identified */
userId?: string;
/** Session ID */
sessionId: string;
}
/** Track event payload */
interface TrackEvent extends BaseEvent {
type: 'track';
event: string;
properties: EventProperties;
}
/** Identify event payload */
interface IdentifyEvent extends BaseEvent {
type: 'identify';
traits: UserTraits;
}
/** Page view event payload */
interface PageEvent extends BaseEvent {
type: 'page';
name: string;
properties: EventProperties & {
url: string;
path: string;
referrer: string;
title: string;
};
}
/** Union of all event types */
type PrivEvent = TrackEvent | IdentifyEvent | PageEvent;
/** Consent status */
interface ConsentState {
granted: boolean;
timestamp: string;
}
/** Batch payload sent to API */
interface BatchPayload {
batch: PrivEvent[];
sdkVersion: string;
sentAt: string;
}Complete Example
import { priv } from '@priv/sdk';
import type { PrivConfig, EventProperties } from '@priv/sdk';
// 1. Configure and initialize
const config: PrivConfig = {
apiKey: process.env.NEXT_PUBLIC_PRIV_KEY!,
endpoint: 'https://api.privlabs.io',
debug: process.env.NODE_ENV === 'development',
autoTrackPageViews: true,
};
priv.init(config);
// 2. Handle consent
function handleConsentDecision(accepted: boolean) {
priv.setConsent(accepted);
if (accepted) {
priv.track('consent_accepted');
}
}
// 3. Identify user on login
function handleLogin(user: { id: string; email: string; plan: string }) {
priv.identify(user.id, {
email: user.email,
plan: user.plan,
});
priv.track('user_logged_in', {
method: 'email',
});
}
// 4. Track events throughout your app
function handlePurchase(product: { id: string; price: number }) {
const properties: EventProperties = {
product_id: product.id,
price: product.price,
currency: 'USD',
};
priv.track('purchase_completed', properties);
}
// 5. Handle logout
function handleLogout() {
priv.track('user_logged_out');
priv.reset();
}
// 6. Cleanup on app close
window.addEventListener('beforeunload', () => {
priv.shutdown();
});Next Steps
- React Integration - React and Next.js patterns
- Configuration - All configuration options