### Start Example App Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/example/README.md Commands to start the example application. Use the repo root as the entry point for yarn workspaces. ```bash # From the repo root yarn example start ``` ```bash yarn example android ``` ```bash yarn example ios ``` -------------------------------- ### Install Example App Dependencies Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/CLAUDE.md Sets up the necessary dependencies for the example React Native application. ```bash yarn example setup ``` -------------------------------- ### Start Metro Bundler for Example App Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/CLAUDE.md Starts the Metro bundler, which is required for running the example app. ```bash yarn example start ``` -------------------------------- ### Install Dependencies for Example App Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/example/README.md Run this command from the repo root to set up all necessary dependencies for the example application, including native dependencies for iOS. ```bash # From the repo root yarn example setup ``` -------------------------------- ### iOS Platform Setup Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/README.md Run pod install for iOS after installing the SDK. ```bash cd ios && pod install ``` -------------------------------- ### Run Example App Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/AGENTS.md Commands to start the Metro bundler and run the example application on iOS and Android. ```bash yarn example start yarn example ios yarn example android ``` -------------------------------- ### Complete Geofencing Setup and Management Example Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/geofencing.md This example demonstrates how to initialize the Klaviyo SDK, request location permissions, register for geofencing, and handle geofencing-related actions like debugging current geofences and unregistering. ```typescript import { useEffect, useRef } from 'react'; import { Klaviyo } from 'klaviyo-react-native-sdk'; import { PermissionsAndroid, Platform } from 'react-native'; export function GeofencingManager() { const permissionRequestedRef = useRef(false); useEffect(() => { const initializeGeofencing = async () => { // Initialize Klaviyo SDK Klaviyo.initialize('YOUR_KLAVIYO_PUBLIC_API_KEY'); // Request location permissions and register geofencing await requestLocationPermission(); }; if (!permissionRequestedRef.current) { initializeGeofencing(); permissionRequestedRef.current = true; } return () => { // Cleanup if needed }; }, []); const requestLocationPermission = async () => { try { if (Platform.OS === 'android') { const permission = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION ); if (permission === 'granted') { Klaviyo.registerGeofencing(); console.log('✓ Geofencing registered'); } else { console.log('✗ Location permission denied'); } } else if (Platform.OS === 'ios') { // iOS: Permission request handled via native AppDelegate // Assume permissions are granted; register geofencing Klaviyo.registerGeofencing(); console.log('✓ Geofencing registered'); } } catch (error) { console.error('Error requesting location permission:', error); } }; const debugCurrentGeofences = () => { Klaviyo.getCurrentGeofences((result) => { console.log('Debug: Currently monitored geofences'); if (result.geofences.length === 0) { console.log(' (none)'); } else { result.geofences.forEach((geofence) => { console.log( ' ID: ' + geofence.identifier ); console.log( ' Location: ' + geofence.latitude + ', ' + geofence.longitude ); console.log( ' Radius: ' + geofence.radius + ' meters' ); }); } }); }; const handleLogout = () => { Klaviyo.unregisterGeofencing(); console.log('Geofencing unregistered'); }; return ( // Your app content ); } ``` -------------------------------- ### Run iOS Example App Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/CLAUDE.md Builds and runs the example application on iOS. ```bash yarn example ios ``` -------------------------------- ### Run Android Example App Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/CLAUDE.md Builds and runs the example application on Android. ```bash yarn example android ``` -------------------------------- ### Install Klaviyo React Native SDK Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/README.md Install the SDK using npm or yarn. ```bash npm install klaviyo-react-native-sdk # or yarn add klaviyo-react-native-sdk ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/AGENTS.md Commands to install project dependencies, build TypeScript code, and run type-checking and linting. ```bash yarn install yarn build yarn typecheck yarn lint yarn test yarn example setup ``` -------------------------------- ### Install Dependencies Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/CLAUDE.md Installs all project dependencies using Yarn. ```bash yarn install ``` -------------------------------- ### Klaviyo SDK Event Tracking Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/event-tracking.md This section demonstrates how to use the `Klaviyo.createEvent` method to track different types of events. It includes examples for predefined events like 'Opened App', 'Viewed Product', 'Added to Cart', and 'Started Checkout', as well as custom events. The examples showcase how to provide event names, values, unique IDs for deduplication, and detailed properties. ```APIDOC ## Klaviyo.createEvent ### Description This method is used to track events within the Klaviyo platform. It allows for sending predefined or custom events with associated values, unique identifiers, and detailed properties. ### Method ``` Klaviyo.createEvent(event: Event) ``` ### Parameters #### Event Object - **name** (`EventName | string`) - Required - Event metric name (max 128 chars). Use `EventName` enum or custom string. - **value** (`number`) - Optional - Numeric value (e.g., purchase amount). - **uniqueId** (`string`) - Optional - Unique ID for deduplication. If omitted, uses timestamp. - **properties** (`EventProperties`) - Optional - Key-value event properties. Limited to 5 MB total, 300 properties, 100 KB per string. ### EventName Enum Predefined Klaviyo events. Use these for standard metrics recognized by Klaviyo. - `ADDED_TO_CART_METRIC` - `OPENED_APP_METRIC` - `STARTED_CHECKOUT_METRIC` - `VIEWED_PRODUCT_METRIC` ### EventProperties Type Key-value mapping for event properties. Keys are strings; values are any JSON-serializable objects. ### Request Example ```typescript // Track app open Klaviyo.createEvent({ name: EventName.OPENED_APP_METRIC, properties: { app_version: '2.1.0', }, }); // Track product view Klaviyo.createEvent({ name: EventName.VIEWED_PRODUCT_METRIC, properties: { product_id: 'SHOES-001', product_name: 'Running Shoes', product_category: 'Footwear', product_price: 129.99, product_url: 'https://shop.example.com/shoes/running-001', }, }); // Track add to cart Klaviyo.createEvent({ name: EventName.ADDED_TO_CART_METRIC, value: 129.99, properties: { product_id: 'SHOES-001', product_name: 'Running Shoes', cart_id: uuidv4(), }, }); // Track checkout initiation const checkoutSessionId = uuidv4(); Klaviyo.createEvent({ name: EventName.STARTED_CHECKOUT_METRIC, value: 129.99, uniqueId: checkoutSessionId, properties: { checkout_id: checkoutSessionId, currency: 'USD', items_count: 1, }, }); // Track purchase completion Klaviyo.createEvent({ name: 'Purchase Completed', value: 129.99, uniqueId: uuidv4(), properties: { order_id: 'ORD-123456', currency: 'USD', items_count: 1, products: [ { id: 'SHOES-001', name: 'Running Shoes', price: 129.99, quantity: 1, }, ], tax: 10.40, shipping: 8.99, discount_code: 'WELCOME10', }, }); // Custom event with complex properties Klaviyo.createEvent({ name: 'Video Watched', value: 100, // Engagement points properties: { video_id: 'vid-789', video_title: 'Product Tutorial', duration_seconds: 145, completion_percent: 100, watched_at: new Date().toISOString(), metadata: { quality: '1080p', subtitles: true, }, }, }); ``` ``` -------------------------------- ### PushNotificationManager Example Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/push-notifications.md A comprehensive example demonstrating how to set up and manage push notifications, including requesting permissions, setting tokens, and handling message events. ```APIDOC ## PushNotificationManager ### Description Manages the lifecycle and events of push notifications within the React Native application. ### Methods - **requestPermission(): Promise** - Requests notification permissions from the user. Returns `true` if granted, `false` otherwise. - **setupPushToken(): Promise** - Retrieves the device's push token (FCM for Android, APNs for iOS) and registers it with the Klaviyo SDK. - **setupTokenRefreshListener(): Function** - Sets up a listener to handle push token refreshes and updates the Klaviyo SDK accordingly. Returns an unsubscribe function. - **setupForegroundMessageHandler(): Function** - Sets up a listener to handle incoming push notifications when the app is in the foreground. Returns an unsubscribe function. - **initialize(): Promise** - Initializes all push notification handling by requesting permissions, setting up the token, and registering listeners. - **updateBadgeCount(count: number): void** - Updates the application's badge count (iOS only). - **getCurrentToken(): string | null** - Returns the currently registered push token. ``` -------------------------------- ### Install Klaviyo React Native SDK with Yarn Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/README.md Use this command to install the SDK using yarn. Ensure you are in your project's root directory. ```sh yarn add klaviyo-react-native-sdk ``` -------------------------------- ### Install Klaviyo React Native SDK with NPM Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/README.md Use this command to install the SDK using npm. Ensure you are in your project's root directory. ```sh npm install klaviyo-react-native-sdk ``` -------------------------------- ### Geofence Object Example Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/geofencing.md An example of how to instantiate a Geofence object with specific properties. This demonstrates the expected format for providing geofence data. ```typescript const geofence: Geofence = { identifier: 'store-123', latitude: 37.7749, longitude: -122.4194, radius: 100, // 100 meters }; ``` -------------------------------- ### Install iOS Dependencies with Cocoapods Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/README.md After installing the npm package, navigate to the 'ios' directory and run this command to install native dependencies using Cocoapods. ```sh pod install ``` -------------------------------- ### Complete Push Notification Manager Example Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/push-notifications.md A comprehensive example demonstrating how to initialize and manage push notifications within a React Native application using the Klaviyo SDK and Firebase Messaging. This includes requesting permissions, setting up push tokens, listening for token refreshes and incoming messages, and handling badge counts. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; import messaging from '@react-native-firebase/messaging'; import { Platform, PermissionsAndroid, useEffect } from 'react-native'; export const PushNotificationManager = { // Request user permission for notifications async requestPermission() { try { if (Platform.OS === 'android') { const permission = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS ); return permission === 'granted'; } else if (Platform.OS === 'ios') { const authStatus = await messaging().requestPermission(); return ( authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL ); } return false; } catch (error) { console.error('Error requesting notification permission:', error); return false; } }, // Get and set push token async setupPushToken() { try { let token: string | null = null; if (Platform.OS === 'android') { token = await messaging().getToken(); console.log('FCM Token:', token); } else if (Platform.OS === 'ios') { token = await messaging().getAPNSToken(); console.log('APNs Token:', token); } if (token) { Klaviyo.setPushToken(token); console.log('Push token registered with Klaviyo'); } } catch (error) { console.error('Error setting up push token:', error); } }, // Listen for token refresh events setupTokenRefreshListener() { const unsubscribe = messaging().onTokenRefresh((token) => { console.log('Push token refreshed:', token); Klaviyo.setPushToken(token); }); return unsubscribe; }, // Handle foreground messages setupForegroundMessageHandler() { const unsubscribe = messaging().onMessage(async (remoteMessage) => { console.log('Foreground message received'); // Show local notification or update UI }); return unsubscribe; }, // Initialize all push notification handling async initialize() { const permissionGranted = await this.requestPermission(); if (permissionGranted) { await this.setupPushToken(); this.setupTokenRefreshListener(); this.setupForegroundMessageHandler(); } }, // Update badge count (iOS only) updateBadgeCount(count: number) { Klaviyo.setBadgeCount(count); }, // Get current push token getCurrentToken() { return Klaviyo.getPushToken(); }, }; // Usage in App Component export function App() { useEffect(() => { // Initialize Klaviyo SDK Klaviyo.initialize('YOUR_KLAVIYO_PUBLIC_API_KEY'); // Initialize push notifications PushNotificationManager.initialize(); }, []); return ; } ``` -------------------------------- ### Firebase Cloud Messaging Setup (React Native) Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/push-notifications.md Guides users through setting up push notifications using Firebase Cloud Messaging in a React Native application. ```APIDOC ## Firebase Cloud Messaging Setup (React Native) ### Description Integrates push notifications using Firebase Cloud Messaging for React Native applications. ### Setup Steps 1. **Request Notification Permissions**: Obtain user consent for notifications. 2. **Fetch and Set Push Token**: Retrieve the device's push token and register it with Klaviyo. 3. **Listen for Token Refresh**: Handle token refreshes to ensure continuous delivery. 4. **Handle Foreground Messages**: Process notifications received while the app is in the foreground. 5. **Handle Background/Terminated Messages (Android)**: Process notifications when the app is in the background or terminated. ### Example ```typescript import messaging from '@react-native-firebase/messaging'; import { Klaviyo } from 'klaviyo-react-native-sdk'; import { Platform, PermissionsAndroid } from 'react-native'; // Request notification permissions const requestNotificationPermission = async () => { try { if (Platform.OS === 'android') { const permission = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS ); return permission === 'granted'; } else if (Platform.OS === 'ios') { const authStatus = await messaging().requestPermission(); return ( authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL ); } } catch (error) { console.error('Permission request error:', error); return false; } }; // Fetch and set push token const fetchAndSetPushToken = async () => { try { let token: string | null = null; if (Platform.OS === 'android') { token = await messaging().getToken(); } else if (Platform.OS === 'ios') { token = await messaging().getAPNSToken(); } if (token) { Klaviyo.setPushToken(token); console.log('Push token updated'); } } catch (error) { console.error('Error fetching token:', error); } }; // Listen for token refresh messaging().onTokenRefresh((token) => { Klaviyo.setPushToken(token); }); // Handle foreground messages messaging().onMessage(async (remoteMessage) => { console.log('Foreground message received:', remoteMessage); // Update UI or show local notification }); // Handle background/terminated messages (Android) messaging().setBackgroundMessageHandler(async (remoteMessage) => { console.log('Background message received:', remoteMessage); }); // Initialize const initializePushNotifications = async () => { const permissionGranted = await requestNotificationPermission(); if (permissionGranted) { await fetchAndSetPushToken(); } }; // Call during app initialization initializePushNotifications(); ``` ``` -------------------------------- ### Complete Profile Management Example Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/profile-management.md Demonstrates initializing the SDK, setting multiple profile attributes at once using `setProfile`, updating individual attributes with `setProfileAttribute`, retrieving current identifiers, and handling user logout with `resetProfile`. ```typescript import { Klaviyo, Profile, ProfileProperty } from 'klaviyo-react-native-sdk'; // Initialize the SDK Klaviyo.initialize('YOUR_KLAVIYO_PUBLIC_API_KEY'); // Example 1: Set multiple profile attributes at once const userProfile: Profile = { email: 'john.doe@example.com', phoneNumber: '+14155552671', externalId: 'customer-12345', firstName: 'John', lastName: 'Doe', title: 'Product Manager', organization: 'Tech Corp', location: { address1: '123 Market St', city: 'San Francisco', region: 'CA', country: 'USA', zip: '94105', timezone: 'America/Los_Angeles', }, properties: { signup_source: 'mobile_app', plan_type: 'premium', }, }; Klaviyo.setProfile(userProfile); // Example 2: Update individual attributes Klaviyo.setProfileAttribute(ProfileProperty.TITLE, 'Senior Product Manager'); Klaviyo.setProfileAttribute('last_login', new Date().toISOString()); // Example 3: Retrieve and check current identifiers const currentEmail = Klaviyo.getEmail(); const currentPhone = Klaviyo.getPhoneNumber(); if (!currentEmail) { Klaviyo.setEmail('john.doe@newemail.com'); } // Example 4: Handle user logout const handleLogout = () => { Klaviyo.resetProfile(); // Navigate to login }; ``` -------------------------------- ### Complete Event Tracking Example Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/event-tracking.md Demonstrates initializing the SDK and tracking various events like app open, product view, add to cart, checkout initiation, purchase completion, and custom events with complex properties. ```typescript import { Klaviyo, Event, EventName } from 'klaviyo-react-native-sdk'; import { v4 as uuidv4 } from 'uuid'; // Initialize Klaviyo.initialize('YOUR_KLAVIYO_PUBLIC_API_KEY'); // Track app open Klaviyo.createEvent({ name: EventName.OPENED_APP_METRIC, properties: { app_version: '2.1.0', }, }); // Track product view Klaviyo.createEvent({ name: EventName.VIEWED_PRODUCT_METRIC, properties: { product_id: 'SHOES-001', product_name: 'Running Shoes', product_category: 'Footwear', product_price: 129.99, product_url: 'https://shop.example.com/shoes/running-001', }, }); // Track add to cart Klaviyo.createEvent({ name: EventName.ADDED_TO_CART_METRIC, value: 129.99, properties: { product_id: 'SHOES-001', product_name: 'Running Shoes', cart_id: uuidv4(), }, }); // Track checkout initiation const checkoutSessionId = uuidv4(); Klaviyo.createEvent({ name: EventName.STARTED_CHECKOUT_METRIC, value: 129.99, uniqueId: checkoutSessionId, properties: { checkout_id: checkoutSessionId, currency: 'USD', items_count: 1, }, }); // Track purchase completion Klaviyo.createEvent({ name: 'Purchase Completed', value: 129.99, uniqueId: uuidv4(), properties: { order_id: 'ORD-123456', currency: 'USD', items_count: 1, products: [ { id: 'SHOES-001', name: 'Running Shoes', price: 129.99, quantity: 1, }, ], tax: 10.40, shipping: 8.99, discount_code: 'WELCOME10', }, }); // Custom event with complex properties Klaviyo.createEvent({ name: 'Video Watched', value: 100, // Engagement points properties: { video_id: 'vid-789', video_title: 'Product Tutorial', duration_seconds: 145, completion_percent: 100, watched_at: new Date().toISOString(), metadata: { quality: '1080p', subtitles: true, }, }, }); ``` -------------------------------- ### Complete User Lifecycle Example Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/README.md Demonstrates the typical flow for managing a user's lifecycle in the app. Includes initialization, tracking anonymous opens, identifying users, tracking actions, setting push tokens, enabling forms, and logging out. ```typescript import { Klaviyo, Profile, ProfileProperty, EventName } from 'klaviyo-react-native-sdk'; // 1. Initialize Klaviyo.initialize('pk_xxx...'); // 2. Track anonymous app open Klaviyo.createEvent({ name: EventName.OPENED_APP_METRIC }); // 3. Identify user (after login) Klaviyo.setProfile({ email: 'user@example.com', firstName: 'John', phoneNumber: '+15555555555', }); // 4. Track user actions Klaviyo.createEvent({ name: EventName.VIEWED_PRODUCT_METRIC, properties: { productId: '123' }, }); // 5. Set push token Klaviyo.setPushToken(fcmToken); // 6. Enable forms Klaviyo.registerForInAppForms(); // 7. Logout (reset profile) Klaviyo.resetProfile(); ``` -------------------------------- ### Register Geofencing Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/README.md Call this method after initializing the Klaviyo SDK to enable geofencing. This allows the SDK to start monitoring geofences configured in your Klaviyo account. ```APIDOC ## Register Geofencing ### Description Enables geofencing support in the Klaviyo SDK. This should be called after the SDK has been initialized with your public API key. ### Method `Klaviyo.registerGeofencing()` ### Parameters None ### Request Example ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; // After initializing with your public API key Klaviyo.registerGeofencing(); ``` ### Response None. This method initiates background monitoring. ``` -------------------------------- ### Register for Geofencing Monitoring Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/main-klaviyo-interface.md Call this method after initializing the SDK and obtaining location permissions to start monitoring geofences configured in your Klaviyo account. The SDK will fetch geofences and track transitions. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; // After initializing and obtaining location permissions Klaviyo.registerGeofencing(); ``` -------------------------------- ### Register Geofencing Monitoring Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/geofencing.md Starts monitoring geofences configured in your Klaviyo account. Requires location permissions to be granted on the device. Must be called after Klaviyo.initialize(). ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; // Start geofence monitoring Klaviyo.registerGeofencing(); ``` -------------------------------- ### Klaviyo SDK Console Logging Examples Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/errors.md Use these console methods to log messages, errors, and warnings from the Klaviyo SDK. Enable logging for debugging purposes. ```typescript // Typical log pattern console.log('[Klaviyo] Message here'); ``` ```typescript // Error condition console.error('[Klaviyo] Error: Something went wrong'); ``` ```typescript // Warning condition console.warn('[Klaviyo] Warning: Something unexpected'); ``` -------------------------------- ### Complete In-App Forms Example Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/in-app-forms.md Initialize Klaviyo, register for in-app forms with a custom session timeout, and set up a handler for form lifecycle events like Shown, Dismissed, and CTAClicked. Includes cleanup logic on component unmount and a logout handler. ```typescript import { useEffect, useRef } from 'react'; import { Klaviyo, FormLifecycleEventType } from 'klaviyo-react-native-sdk'; export function FormManager() { const unsubscribeRef = useRef<(() => void) | null>(null); useEffect(() => { // Initialize Klaviyo Klaviyo.initialize('YOUR_KLAVIYO_PUBLIC_API_KEY'); // Register for in-app forms with custom timeout Klaviyo.registerForInAppForms({ sessionTimeoutDuration: 1800, // 30 minutes }); // Register form lifecycle handler unsubscribeRef.current = Klaviyo.registerFormLifecycleHandler((event) => { switch (event.type) { case FormLifecycleEventType.Shown: console.log(`📋 Form shown: ${event.formName}`); logAnalytics('form_shown', { form_id: event.formId, form_name: event.formName, }); break; case FormLifecycleEventType.Dismissed: console.log(`✕ Form dismissed: ${event.formName}`); logAnalytics('form_dismissed', { form_id: event.formId, form_name: event.formName, }); break; case FormLifecycleEventType.CtaClicked: console.log( `👆 CTA clicked: "${event.buttonLabel}" -> ${event.deepLinkUrl}` ); logAnalytics('form_cta_clicked', { form_id: event.formId, form_name: event.formName, button_label: event.buttonLabel, deep_link_url: event.deepLinkUrl, }); break; } }); // Cleanup on unmount return () => { unsubscribeRef.current?.(); }; }, []); const handleLogout = () => { Klaviyo.unregisterFromInAppForms(); unsubscribeRef.current?.(); }; return ( // Your app content ); } function logAnalytics(event: string, data: any) { // Send to your analytics service console.log(`Analytics: ${event}`, data); } ``` -------------------------------- ### Setup Push Notifications with Firebase Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/README.md Configures push notifications using Firebase Cloud Messaging. Requests user permission, retrieves the device token, and sets it in the Klaviyo SDK. Includes listening for token refreshes. ```typescript import messaging from '@react-native-firebase/messaging'; const setupPushNotifications = async () => { // Request permission const authStatus = await messaging().requestPermission(); const isEnabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL; if (isEnabled) { // Get and set token const token = Platform.OS === 'ios' ? await messaging().getAPNSToken() : await messaging().getToken(); Klaviyo.setPushToken(token); // Listen for token refresh messaging().onTokenRefresh((newToken) => { Klaviyo.setPushToken(newToken); }); } }; ``` -------------------------------- ### Define and Use EventProperties Type Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/event-tracking.md This example demonstrates how to define and use the `EventProperties` type for custom event data. It shows creating a 'Product Viewed' event with various property types including strings, booleans, arrays, and numbers. ```typescript import { Klaviyo, EventProperties } from 'klaviyo-react-native-sdk'; const properties: EventProperties = { screen_name: 'ProductDetail', product_id: 'SKU-12345', category: 'Electronics', is_on_sale: true, rating: 4.5, tags: ['featured', 'new'], }; Klaviyo.createEvent({ name: 'Product Viewed', properties, }); ``` -------------------------------- ### iOS Podfile Configuration for Location/Geofencing Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/errors.md To enable the Klaviyo Location/Geofencing module on iOS, ensure the KLAVIYO_INCLUDE_LOCATION environment variable is not set to 'false' in your Podfile. After modifying the Podfile, run 'pod install'. ```ruby # Podfile: Remove or comment out this line # ENV['KLAVIYO_INCLUDE_LOCATION'] = 'false' # Then run: pod install ``` -------------------------------- ### Klaviyo.createEvent with Predefined Events Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/event-tracking.md Track common Klaviyo-defined events using the `EventName` enum. This method allows you to log user interactions like adding to cart, opening the app, starting checkout, or viewing a product. ```APIDOC ## Klaviyo.createEvent with Predefined Events ### Description Track common Klaviyo-defined events using the `EventName` enum. This method allows you to log user interactions like adding to cart, opening the app, starting checkout, or viewing a product. ### Method `createEvent` ### Parameters #### Properties - **name** (EventName) - Required - The name of the event, selected from the `EventName` enum. - **value** (number) - Optional - The monetary value associated with the event. - **properties** (object) - Optional - A key-value map of additional properties for the event. - **product_id** (string) - Required for product-related events - The unique identifier for the product. - **product_name** (string) - Optional - The name of the product. ### Request Example ```typescript import { Klaviyo, EventName } from 'klaviyo-react-native-sdk'; // Track product view Klaviyo.createEvent({ name: EventName.VIEWED_PRODUCT_METRIC, properties: { product_id: 'SKU-42', }, }); // Track cart addition Klaviyo.createEvent({ name: EventName.ADDED_TO_CART_METRIC, value: 19.99, properties: { product_id: 'SKU-42', product_name: 'Awesome Product', }, }); ``` ### Response This method does not return a value. ``` -------------------------------- ### Validate Klaviyo Tracking Links Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/errors.md Demonstrates how to use handleUniversalTrackingLink to validate different URL inputs. It shows examples of null, empty, invalid format, and valid Klaviyo tracking links, along with their expected return values. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; // Empty/null (logged as error) Klaviyo.handleUniversalTrackingLink(null); // returns false Klaviyo.handleUniversalTrackingLink(''); // returns false Klaviyo.handleUniversalTrackingLink(' '); // returns false // Invalid format (logged as warning) Klaviyo.handleUniversalTrackingLink('not-a-url'); // returns false Klaviyo.handleUniversalTrackingLink('http://example.com/u/123'); // HTTP, not HTTPS, returns false Klaviyo.handleUniversalTrackingLink('https://example.com/other'); // wrong path, returns false // Valid (no logs, returns true) Klaviyo.handleUniversalTrackingLink('https://klvx.co/u/abc123'); // returns true ``` -------------------------------- ### Basic SDK Usage Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/README.md Initialize the SDK, set a user profile, track an event, set a push token, and register for in-app forms. ```typescript import { Klaviyo, Profile } from 'klaviyo-react-native-sdk'; // Initialize with your public API key Klaviyo.initialize('YOUR_KLAVIYO_PUBLIC_API_KEY'); // Set a user profile Klaviyo.setProfile({ email: 'user@example.com', firstName: 'John', lastName: 'Doe', }); // Track an event Klaviyo.createEvent({ name: 'Purchase Completed', value: 99.99, properties: { orderId: '12345', }, }); // Set push token for notifications Klaviyo.setPushToken('fcm_or_apns_token'); // Register for in-app forms Klaviyo.registerForInAppForms(); ``` -------------------------------- ### Initialization Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/MANIFEST.md Initializes the Klaviyo SDK with your public API key. ```APIDOC ## Klaviyo.initialize() ### Description Initializes the Klaviyo SDK. This function must be called before any other Klaviyo SDK functions. ### Method `initialize(apiKey: string, options?: InitializationOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript Klaviyo.initialize('YOUR_PUBLIC_API_KEY'); ``` ### Response #### Success Response (void) This function does not return a value upon successful initialization. #### Response Example None ``` -------------------------------- ### Get Email Address Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/profile-management.md Retrieve the email address of the current profile. This can be done synchronously or asynchronously with a callback. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; // Synchronous retrieval const currentEmail = Klaviyo.getEmail(); console.log('Current email:', currentEmail); // Async retrieval with callback Klaviyo.getEmail((email) => { console.log('Email from callback:', email); }); ``` -------------------------------- ### Get Email Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/main-klaviyo-interface.md Retrieve the email address of the current profile. An optional callback function can be provided to handle the result. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; const email = Klaviyo.getEmail((result) => { console.log('Email:', result); }); ``` -------------------------------- ### Initialize Klaviyo SDK Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/configuration.md Initialize the SDK with your public API key. This is a required step before using other SDK functionalities. Obtain your public API key from your Klaviyo dashboard. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; Klaviyo.initialize('YOUR_KLAVIYO_PUBLIC_API_KEY'); ``` -------------------------------- ### Main SDK Exports Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/module-architecture.md The main entry point exports the Klaviyo singleton instance and various public types for event and profile management. Ensure all necessary types are imported for use. ```typescript export const Klaviyo: KlaviyoInterface = { ... }; export type { Event, EventProperties, EventName } from './Event'; export type { Profile, ProfileProperties, ProfilePropertyKey, Location } from './Profile'; // ... more exports ``` -------------------------------- ### Get Phone Number Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/main-klaviyo-interface.md Retrieve the phone number of the current profile. An optional callback function can be provided to handle the result. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; const phone = Klaviyo.getPhoneNumber((result) => { console.log('Phone:', result); }); ``` -------------------------------- ### Get Phone Number Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/profile-management.md Retrieve the phone number of the current profile. This can be done synchronously or asynchronously with a callback. The returned number will be in E.164 format. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; // Synchronous retrieval const currentPhone = Klaviyo.getPhoneNumber(); console.log('Current phone:', currentPhone); // Async retrieval with callback Klaviyo.getPhoneNumber((phone) => { console.log('Phone from callback:', phone); }); ``` -------------------------------- ### KlaviyoPushApi Interface Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/push-notifications.md Defines the interface for interacting with push notification functionalities, including setting and getting the push token, and managing the badge count. ```typescript interface KlaviyoPushApi { setPushToken(token: string): void; getPushToken(callback: Function | undefined): string | null; setBadgeCount(count: number): void; } ``` -------------------------------- ### Get Push Token from Klaviyo SDK Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/main-klaviyo-interface.md Retrieve the push token of the current profile. An optional callback function can be provided to handle the result asynchronously. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; const token = Klaviyo.getPushToken((result) => { console.log('Push token:', result); }); ``` -------------------------------- ### Run Tests Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/CLAUDE.md Executes the project's test suite. ```bash yarn test ``` -------------------------------- ### Get External ID Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/profile-management.md Retrieve the external ID of the current profile. This can be done synchronously or asynchronously with a callback. The external ID is a unique identifier from your system. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; // Synchronous retrieval const currentExternalId = Klaviyo.getExternalId(); console.log('External ID:', currentExternalId); // Async retrieval with callback Klaviyo.getExternalId((id) => { console.log('External ID from callback:', id); }); ``` -------------------------------- ### Configure SDK with Local or Remote Dependencies Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/AGENTS.md Script to configure the SDK to use local or remote versions of native Android and iOS SDKs for testing. ```bash # Configure both platforms to default local paths ./configure-sdk.sh -l # Optionally override the path, or specify whether to configure android or iOS only ./configure-sdk.sh -l -a ../klaviyo-android-sdk-worktree # Configure specific remote dependency by version, commit hash, or branch name ./configure-sdk.sh -r --android=COMMIT_HASH_OR_BRANCH_NAME --ios=COMMIT_HASH_OR_BRANCH_NAME ``` -------------------------------- ### Configure SDK with Local Paths Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/CLAUDE.md Configures the SDK to use local paths for both Android and iOS native dependencies. Use this for testing local changes across all three SDKs. ```bash ./configure-sdk.sh -l ``` -------------------------------- ### Get Current Push Token Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/push-notifications.md Retrieves the push token currently associated with the profile. This can be done synchronously or asynchronously using an optional callback function. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; // Synchronous retrieval const currentToken = Klaviyo.getPushToken(); if (currentToken) { console.log('Current push token:', currentToken); } else { console.log('No push token set'); } // Asynchronous retrieval with callback Klaviyo.getPushToken((token) => { console.log('Push token from callback:', token); }); ``` -------------------------------- ### Initialize Klaviyo SDK Early Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/errors.md Initialize the Klaviyo SDK as early as possible in your application lifecycle to ensure all subsequent method calls are processed correctly. This prevents operations from being queued as errors. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; import { useEffect } from 'react'; export function App() { useEffect(() => { // Initialize as early as possible Klaviyo.initialize('YOUR_KLAVIYO_PUBLIC_API_KEY'); }, []); return ; } ``` -------------------------------- ### Set Minimum iOS Version in Podfile Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/Troubleshooting.md Update your Podfile to specify a minimum iOS version of 13.0 to resolve CocoaPods installation issues related to deployment targets. ```ruby MIN_IOS_OVERRIDE = '13.0' if Gem::Version.new(MIN_IOS_OVERRIDE) > Gem::Version.new(min_ios_version_supported) min_ios_version_supported = MIN_IOS_OVERRIDE end # existing code platform :ios, min_ios_version_supported ``` -------------------------------- ### Singleton Implementation of KlaviyoInterface Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/module-architecture.md This snippet shows the singleton pattern used for the Klaviyo interface, where most methods directly call the native SDK bridge. It demonstrates the initialization and profile setting methods. ```typescript export const Klaviyo: KlaviyoInterface = { initialize(apiKey: string): void { KlaviyoReactNativeSdk.initialize(apiKey); }, // Profile methods setProfile(profile: Profile): void { KlaviyoReactNativeSdk.setProfile(formatProfile(profile)); }, // ... other methods }; ``` -------------------------------- ### Set Push Token in Klaviyo SDK Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/main-klaviyo-interface.md Set the push token for the current profile. This token is obtained from FCM (Android) or APNs (iOS). Ensure you have `@react-native-firebase/messaging` installed and configured. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; import messaging from '@react-native-firebase/messaging'; const fetchAndSetPushToken = async () => { const token = await messaging().getToken(); Klaviyo.setPushToken(token); }; ``` -------------------------------- ### Exclude In-App Forms Module (iOS) Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/in-app-forms.md Configure your Podfile to exclude the In-App Forms module to reduce binary size on iOS. Run `pod install` after modifying the Podfile. ```ruby ENV['KLAVIYO_INCLUDE_FORMS'] = 'false' target 'YourApp' do # ... your pod configuration end ``` -------------------------------- ### Call getLaunchOptionsWithURL in AppDelegate Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/Troubleshooting.md Ensure the `getLaunchOptionsWithURL` method is called within your `application:didFinishLaunchingWithOptions:` method before invoking the superclass method. Pass the modified launch options to correctly handle deep links from terminated app states. ```objective-c - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.moduleName = @"KlaviyoReactNativeSdkExample"; self.initialProps = @{}; // some more code ... NSMutableDictionary * launchOptionsWithURL = [self getLaunchOptionsWithURL:launchOptions]; return [super application:application didFinishLaunchingWithOptions:launchOptionsWithURL]; } ``` -------------------------------- ### API Extension Pattern with Interface Composition Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/module-architecture.md Demonstrates how the SDK extends the main KlaviyoInterface by composing feature-specific APIs. The implementation provides all extended methods. ```typescript export interface KlaviyoEventAPI { createEvent(event: Event): void; } export interface KlaviyoInterface extends KlaviyoEventAPI, KlaviyoProfileApi, KlaviyoPushApi, KlaviyoGeofencingApi, KlaviyoFormsApi, KlaviyoDeepLinkAPI { initialize(apiKey: string): void; } export const Klaviyo: KlaviyoInterface = { createEvent(event: Event): void { ... }, setProfile(profile: Profile): void { ... }, initialize(apiKey: string): void { ... }, }; ``` -------------------------------- ### Unregister from In-App Forms Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/main-klaviyo-interface.md Disable in-app form delivery. This is typically used during user logout or when a user opts out of forms. The next call to `registerForInAppForms()` will start a new session. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; Klaviyo.unregisterFromInAppForms(); ``` -------------------------------- ### Reset Current Profile Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/README.md Call this method to clear all currently tracked profile identifiers. This is typically used when a user logs out or when you need to start tracking a completely new profile. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; Klaviyo.resetProfile(); ``` -------------------------------- ### iOS Podfile Configuration for Forms Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/errors.md To enable the Klaviyo Forms module on iOS, ensure the KLAVIYO_INCLUDE_FORMS environment variable is not set to 'false' in your Podfile. After modifying the Podfile, run 'pod install'. ```ruby # Podfile: Remove or comment out this line # ENV['KLAVIYO_INCLUDE_FORMS'] = 'false' # Then run: pod install ``` -------------------------------- ### Register for Geofencing Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/README.md Enable geofencing monitoring by calling `registerGeofencing()` after initializing the Klaviyo SDK. This function should be called after the SDK has been set up with your public API key. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; // After initializing with your public API key Klaviyo.registerGeofencing(); ``` -------------------------------- ### Get Current Geofences Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/geofencing.md Retrieves the list of currently monitored geofences. This method is intended for debugging and internal use, and its API may change without notice. It invokes a callback with the geofences array. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; Klaviyo.getCurrentGeofences((result) => { console.log('Currently monitored geofences:'); result.geofences.forEach((geofence) => { console.log( ` ${geofence.identifier}: ${geofence.latitude}, ${geofence.longitude} (${geofence.radius}m)` ); }); }); ``` -------------------------------- ### Create Event with Detailed Properties Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/api-reference/event-tracking.md Use this snippet to create a 'Purchase Completed' event with standard order details, product information, and custom properties. Ensure the Klaviyo SDK is imported. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; Klaviyo.createEvent({ name: 'Purchase Completed', value: 149.99, properties: { // Standard properties order_id: 'ORD-12345', currency: 'USD', // Product information products: [ { id: 'SKU-A', name: 'Item A', price: 50.00, quantity: 1 }, { id: 'SKU-B', name: 'Item B', price: 49.99, quantity: 2 }, ], // Custom properties shipping_method: 'express', gift_message: 'Happy Birthday!', loyalty_points_earned: 150, }, }); ``` -------------------------------- ### Configure In-App Forms Session Timeout Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/README.md Customize the session timeout duration for In-App Forms by passing a `FormConfiguration` object with `sessionTimeoutDuration` to `registerForInAppForms()`. This example sets the timeout to 30 minutes (1800 seconds). ```javascript import { Klaviyo } from "klaviyo-react-native-sdk"; let config: FormConfiguration = { sessionTimeoutDuration: 1800 } Klaviyo.registerForInAppForms(config); ``` -------------------------------- ### Initialize Klaviyo SDK in React Native Source: https://github.com/klaviyo/klaviyo-react-native-sdk/blob/master/_autodocs/configuration.md Initialize the Klaviyo SDK from your React Native application's root component or initialization code using your public API key. ```typescript import { Klaviyo } from 'klaviyo-react-native-sdk'; // In your app's root component or initialization code Klaviyo.initialize('YOUR_KLAVIYO_PUBLIC_API_KEY'); ```