Skip to content

API Reference

Complete reference for all Tappd Web SDK methods and APIs.

Core Methods

identify(attributes)

Identify or update a customer using your internal user ID. Automatically merges anonymous data if user was previously anonymous. The SDK generates an internal identifier automatically.

Parameters:

ParameterTypeRequiredDescription
attributesCustomerAttributesYesUser attributes - must include external_id

Returns: Promise<void>

Example:

javascript
await tappd.identify({
  external_id: 'ext_123',  // Required: Your internal user ID from your database/system
  name: 'John Doe',
  email: 'john@example.com',
  phone: '+1234567890',
  // Custom attributes
  age: 28,
  plan: 'premium',
  company: 'Acme Corp'
});

Understanding external_id:

  • external_id ('ext_123'):
    • Required - Your internal user identifier from your own system/database
    • Used as the primary way to identify users (no need to pass userId)
    • SDK automatically generates an internal userId based on your external_id
    • Used to link all events, sessions, and data to this user
    • Should be unique and stable (e.g., your database user ID)
    • All future track() calls will be associated with this user

Simplified API:

The SDK now simplifies identification - you only need to provide your external_id:

javascript
// ✅ Simple - just pass your internal user ID
await tappd.identify({
  external_id: 'user_123',  // Your database user ID
  email: 'john@example.com',
  name: 'John Doe'
});

// SDK automatically:
// 1. Generates internal userId
// 2. Creates/finds customer by external_id
// 3. Links all events to this user

What happens if external_id is not provided?

  • If identify() is never called:

    • User remains anonymous
    • All events are tracked with an anonymousId (automatically generated)
    • Events can be merged later when identify() is called with external_id
  • If identify() is called without external_id:

    • SDK throws an error: "external_id is required in attributes"
    • Event is not processed

How it works:

  1. Identification: Pass your external_id - SDK handles the rest
  2. Event Tracking: All events tracked with track() are automatically associated with this user
  3. Session Linking: All sessions are linked to the user
  4. Data Merging: When you call identify(), any anonymous events tracked before identification are automatically merged to this user
  5. User Lookup: Query and filter data by external_id in the Tappd dashboard

Best Practices:

  • Always include external_id in your identify() call (it's required)
  • Use a stable, unique identifier from your system (e.g., database user ID)
  • Call identify() after user login/signup to link events to the user
  • Keep the same external_id for a user across sessions and devices

CustomerAttributes Interface:

typescript
interface CustomerAttributes {
  external_id: string; // Required: Your internal user ID
  name?: string;
  email?: string;
  phone?: string;
  [key: string]: any; // Custom attributes
}

track(eventName, properties?)

Track a custom event with optional properties.

Parameters:

ParameterTypeRequiredDescription
eventNamestringYesName of the event to track
propertiesEventPropertiesNoAdditional event properties

Returns: Promise<void>

Example:

javascript
await tappd.track('purchase', {
  amount: 99.99,
  currency: 'USD',
  productId: 'prod_123',
  productName: 'Pro Plan'
});

EventProperties Interface:

typescript
interface EventProperties {
  [key: string]: any;
}

trackPageView(url?, properties?)

Manually track a page view. Page views are automatically tracked if autoTrack: true.

Parameters:

ParameterTypeRequiredDescription
urlstringNoPage URL (defaults to current URL)
propertiesEventPropertiesNoAdditional page view properties

Returns: Promise<void>

Example:

javascript
// Track current page
await tappd.trackPageView();

// Track specific URL
await tappd.trackPageView('https://example.com/pricing', {
  referrer: 'google.com'
});

setExternalId(externalId)

Set the external ID for the current user. User must be identified first.

Parameters:

ParameterTypeRequiredDescription
externalIdstringYesExternal user identifier

Returns: Promise<void>

Example:

javascript
await tappd.setExternalId('ext_user_123');

Throws: Error if user is not identified


setUserAttributes(attributes)

Update user attributes for the current user. User must be identified first.

Parameters:

ParameterTypeRequiredDescription
attributesCustomerAttributesYesAttributes to update

Returns: Promise<void>

Example:

javascript
await tappd.setUserAttributes({
  plan: 'enterprise',
  lastLogin: new Date().toISOString(),
  status: 'active'
});

Throws: Error if user is not identified


setCustomAttributes(attributes)

Set custom user attributes. User must be identified first.

Parameters:

ParameterTypeRequiredDescription
attributesRecord<string, any>YesCustom attributes object

Returns: Promise<void>

Example:

javascript
await tappd.setCustomAttributes({
  preferences: {
    theme: 'dark',
    language: 'en'
  },
  customField: 'value'
});

Throws: Error if user is not identified


Utility Methods

getSessionId()

Get the current session ID.

Returns: string | null

Example:

javascript
const sessionId = tappd.getSessionId();
console.log('Session ID:', sessionId);
// Output: sess_abc123def456

getAnonymousId()

Get the anonymous ID (persists across sessions until user is identified).

Returns: string

Example:

javascript
const anonymousId = tappd.getAnonymousId();
console.log('Anonymous ID:', anonymousId);
// Output: anon_xyz789ghi012

reset()

Reset the SDK state. Clears user data and starts a new session. Useful for logout.

Returns: void

Example:

javascript
// On user logout
function handleLogout() {
  tappd.reset();
  // User is now anonymous again
}

In-App Messages

getInAppMessages()

Fetch pending in-app messages for the current user.

Returns: Promise<InAppMessage[]>

Example:

javascript
const messages = await tappd.getInAppMessages();
messages.forEach(message => {
  console.log(`Message: ${message.config.messageType}`);
  console.log(`Status: ${message.status}`);
});

displayInAppMessage(message)

Display a specific in-app message.

Parameters:

ParameterTypeRequiredDescription
messageInAppMessageYesThe message object to display

Returns: Promise<void>

Example:

javascript
const messages = await tappd.getInAppMessages();
if (messages.length > 0) {
  await tappd.displayInAppMessage(messages[0]);
}

displayPendingMessages()

Fetch and display all pending messages that are ready to be shown.

Returns: Promise<void>

Example:

javascript
// Manually trigger message display
await tappd.displayPendingMessages();

dismissMessage(messageId)

Dismiss a message and track the dismissal event.

Parameters:

ParameterTypeRequiredDescription
messageIdstringYesThe ID of the message to dismiss

Returns: Promise<void>

Example:

javascript
await tappd.dismissMessage('message_id_123');

trackMessageEvent(messageId, eventType, metadata)

Track a custom message interaction event.

Parameters:

ParameterTypeRequiredDescription
messageIdstringYesThe ID of the message
eventTypestringYesEvent type (e.g., 'viewed', 'clicked', 'dismissed')
metadataobjectNoAdditional event metadata

Returns: Promise<void>

Example:

javascript
await tappd.trackMessageEvent('message_id_123', 'clicked', {
  buttonText: 'Get Started',
  buttonLink: '/signup'
});

See also: In-App Messages Guide for detailed documentation.


Push Notifications

getVapidPublicKey()

Get the VAPID public key for web push subscriptions.

Returns: Promise<string> - VAPID public key

Example:

javascript
const publicKey = await tappd.getVapidPublicKey();
console.log('VAPID Public Key:', publicKey);

isSubscribed()

Check if the current user is subscribed to push notifications.

Returns: Promise<boolean> - true if subscribed, false otherwise

Example:

javascript
const isSubscribed = await tappd.isSubscribed();
if (isSubscribed) {
  console.log('User is subscribed to push notifications');
} else {
  console.log('User is not subscribed');
}

subscribeToPush(options?)

Subscribe the current user to push notifications. User must be identified first.

Parameters:

ParameterTypeRequiredDescription
optionsPushSubscriptionOptionsNoOptional subscription options

Returns: Promise<PushSubscription> - Push subscription object

Throws: Error if:

  • Push notifications are not supported
  • Notification permission is denied
  • User is not identified

Example:

javascript
// Identify user first (required)
await tappd.identify({
  external_id: 'user_123',
  email: 'john@example.com'
});

// Subscribe to push notifications
try {
  const subscription = await tappd.subscribeToPush();
  console.log('Successfully subscribed:', subscription.endpoint);
} catch (error) {
  console.error('Subscription failed:', error);
}

unsubscribeFromPush()

Unsubscribe the current user from push notifications.

Returns: Promise<void>

Example:

javascript
try {
  await tappd.unsubscribeFromPush();
  console.log('Successfully unsubscribed from push notifications');
} catch (error) {
  console.error('Unsubscribe failed:', error);
}

showPermissionPrompt(type)

Show a permission prompt to the user. Supported types: 'slidedown', 'bell', or 'native'.

Parameters:

ParameterTypeRequiredDescription
type'slidedown' | 'bell' | 'native'YesType of permission prompt

Returns: Promise<void>

Example:

javascript
// Show native browser prompt
await tappd.showPermissionPrompt('native');

// Show slidedown prompt
await tappd.showPermissionPrompt('slidedown');

// Show bell icon prompt
await tappd.showPermissionPrompt('bell');

Note: After showing the prompt, you should call subscribeToPush() when the user grants permission.


hidePermissionPrompt()

Hide any active permission prompt.

Returns: Promise<void>

Example:

javascript
// Hide active prompt
await tappd.hidePermissionPrompt();

Types

TappdConfig

SDK configuration interface.

typescript
interface TappdConfig {
  appId: string;                    // Required
  apiUrl?: string;                  // Optional
  autoTrack?: boolean;              // Optional, default: true
  sessionTimeout?: number;          // Optional, default: 30
  enableAutoCapture?: boolean;      // Optional, default: false
  debug?: boolean;                  // Optional, default: false
  enableInAppMessages?: boolean;    // Optional, default: true
  autoDisplayMessages?: boolean;    // Optional, default: true
  messagePollingInterval?: number;  // Optional, default: 30 (seconds)
  messageContainerId?: string;      // Optional: Custom DOM container ID
}

CustomerAttributes

User attributes interface.

typescript
interface CustomerAttributes {
  name?: string;
  email?: string;
  phone?: string;
  external_id?: string;
  [key: string]: any; // Any custom attributes
}

EventProperties

Event properties interface.

typescript
interface EventProperties {
  [key: string]: any; // Any properties
}

Error Handling

All async methods return promises and can throw errors. Always use try-catch:

javascript
try {
  await tappd.identify({
    external_id: 'user_123',
    email: 'john@example.com'
  });
} catch (error) {
  console.error('Identification failed:', error);
}

try {
  await tappd.track('purchase', { amount: 99.99 });
} catch (error) {
  console.error('Tracking failed:', error);
}

Common errors:

  • Network errors: API request failed
  • Invalid App ID: App ID not found or invalid
  • User not identified: Calling methods that require identification before identify() is called

Next Steps

Released under the MIT License.