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.priv.io/v1',
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: 'John Doe',
plan: 'pro',
company: 'Acme Inc',
created_at: '2024-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();
};
}, []);TypeScript Types
Import types for full type safety:
import type {
PrivConfig,
EventProperties,
UserTraits,
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>;
/** Track event payload */
interface TrackEvent {
type: 'track';
event: string;
properties: EventProperties;
timestamp: string;
anonymousId: string;
userId?: string;
sessionId: string;
}
/** Identify event payload */
interface IdentifyEvent {
type: 'identify';
traits: UserTraits;
timestamp: string;
anonymousId: string;
userId?: string;
sessionId: string;
}
/** Page view event payload */
interface PageEvent {
type: 'page';
name: string;
properties: EventProperties & {
url: string;
path: string;
referrer: string;
title: string;
};
timestamp: string;
anonymousId: string;
userId?: string;
sessionId: string;
}
/** Consent status */
interface ConsentState {
granted: boolean;
timestamp: 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.priv.io/v1',
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