PRIV ProtocolPRIV Docs
Analytics SDK

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:

NameTypeRequiredDescription
config.apiKeystringYesYour PRIV API key
config.endpointstringYesAnalytics endpoint URL
config.debugbooleanNoEnable debug logging
config.flushIntervalnumberNoFlush interval in ms (default: 5000)
config.flushAtnumberNoEvents before auto-flush (default: 10)
config.autoTrackPageViewsbooleanNoAuto-track pages (default: true)
config.autoTrackClicksbooleanNoAuto-track clicks (default: false)
config.autoTrackScrollbooleanNoAuto-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:

NameTypeRequiredDescription
eventstringYesEvent name (e.g., 'button_click')
propertiesEventPropertiesNoAdditional 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:

NameTypeRequiredDescription
namestringNoPage name (defaults to document title)
propertiesEventPropertiesNoAdditional page data

Auto-captured Properties:

The SDK automatically captures:

  • url - Full page URL
  • path - URL pathname
  • referrer - Document referrer
  • title - 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:

NameTypeRequiredDescription
userIdstringYesUnique user identifier
traitsUserTraitsNoUser 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

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:

NameTypeRequiredDescription
grantedbooleanYesWhether consent is granted

Returns: void

GDPR Compliance:

The SDK is designed for GDPR compliance:

  1. Initialize the SDK (no tracking yet)
  2. Show consent banner to user
  3. Call setConsent(true) when user accepts
  4. 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