UNPKG

@coho-ai/sdk

Version:

Coho AI SDK for Web Applications

222 lines (174 loc) β€’ 5.58 kB
# Coho AI Web SDK A TypeScript/JavaScript SDK for integrating Coho AI into web applications. ## Features - πŸ”„ Automatic retry mechanism for failed requests - 🌍 Multi-region support (EU/US) - πŸ“± Automatic device and platform detection - πŸ” Rich event tracking capabilities - πŸ“ŠοΈ Configurable logging and debugging - 🌐 Support for user-defined proxy endpoints - πŸ“Š TypeScript support with type definitions ## Installation ```bash # Using npm npm install @coho-ai/sdk # Using yarn yarn add @coho-ai/sdk # Using pnpm pnpm add @coho-ai/sdk ``` ## Quick Start ```typescript import { CohoSDK, Region } from '@coho-ai/sdk'; // Initialize the SDK const sdk = new CohoSDK({ tenantId: 'your-tenant-id', region: Region.EU }); // Make sure you set the user ID before sending events sdk.setUserId('user-123'); // Track an event await sdk.sendEvent('page_view', { page: '/home', referrer: document.referrer }); ``` ## Configuration Options | Option | Type | Default | Description | |----------------|-----------|-------------|--------------------------------------------------| | `tenantId` | `string` | Required | Your Coho Analytics tenant ID | | `region` | `Region` | `Region.EU` | Data center region (EU or US) | | `retries` | `number` | `3` | Number of retry attempts for failed requests | | `retryDelay` | `number` | `1000` | Delay between retries in milliseconds | | `enableLogging`| `boolean` | `false` | Enable debug logging | | `proxyEndpoint`| `string` | `undefined` | Optional user-defined proxy endpoint for requests | ## Using Proxy Endpoints The SDK now supports sending events through a user-defined proxy endpoint. This allows you to route your requests through a specific URL, which can be useful for various scenarios, such as logging, monitoring, or compliance. ### Important Note on Proxy Functionality When using a proxy endpoint, it is essential that the proxy server captures the incoming request and forwards it to the appropriate Coho URL: ``` "https://app.coho.ai/api/raw-data/custom" ``` The proxy must also ensure that all headers are preserved during this forwarding process. This includes headers such as: - `X-Coho-TenantId`: "Your Coho tenant ID" - `X-Coho-UserId-Key`: "userId" //The user ID key - `Accept`: "*/*" - `Content-Type`: `application/json` - `X-Coho-DatasourceContext`: "sdk" ### Example Usage with Proxy ```typescript const sdk = new CohoSDK({ tenantId: 'your-tenant-id', proxyEndpoint: 'your-proxy-endpoint' // Define your proxy endpoint }); // Set user ID sdk.setUserId('user-456'); // Send an event await sdk.sendEvent('button_click', { buttonId: 'submit-button', timestamp: new Date().toISOString() }); ``` ## Global Properties The SDK allows you to set global properties that will be included in every event sent. This is useful for tracking user-specific or session-specific data across multiple events. ### Setting Global Properties You can set global properties using the `setGlobalProperties` method. This method accepts an object containing key-value pairs of properties. ```typescript // Set global properties sdk.setGlobalProperties({ user_type: "premium", campaign: "winter" }); ``` ### Example Usage Here’s an example of how to set global properties and send an event: ```typescript // Initialize the SDK const sdk = new CohoSDK({ tenantId: 'your-tenant-id' }); // Set user ID sdk.setUserId('user-123'); // Set global properties sdk.setGlobalProperties({ user_type: "premium", campaign: "winter" }); // Send an event await sdk.sendEvent('page_view', { page: '/home', referrer: document.referrer }); ``` ## Framework Integration Examples ### React ```tsx import { CohoAiProvider, useCohoAi } from "@coho-ai/sdk/react"; import { Region } from "@coho-ai/sdk"; // Wrap your app with the provider const App = () => ( <CohoAiProvider tenantId="your-tenant-id"> <YourApp /> </CohoAiProvider> ); // Use in components const YourComponent = () => { const cohoAi = useCohoAi(); // Set global properties when the component mounts or based on some action React.useEffect(() => { cohoAi.setGlobalProperties({ user_type: "premium", campaign: "winter" }); }, [cohoAi]); const handleClick = () => { cohoAi.setUserId('user-123'); cohoAi.sendEvent("button_clicked", { location: "homepage" }); }; return <button onClick={handleClick}>Click Me</button>; }; ``` ### Vue 3 ```typescript import { createApp } from 'vue'; import { CohoSDK, Region } from '@coho/sdk'; const app = createApp({ created() { const sdk = new CohoSDK({ tenantId: import.meta.env.VITE_COHO_TENANT_ID, region: Region.EU }); // Make SDK available throughout the app app.config.globalProperties.$coho = sdk; } }); ``` ## TypeScript Support The SDK includes full TypeScript support with type definitions for better developer experience: ```typescript interface PurchaseEvent { orderId: string; total: number; currency: string; items: Array<{ productId: string; name: string; price: number; quantity: number; }>; } // TypeScript will enforce the event payload structure await sdk.sendEvent<PurchaseEvent>('purchase_completed', { orderId: '12345', total: 99.99, currency: 'USD', items: [{ productId: 'prod-1', name: 'Widget', price: 49.99, quantity: 2 }] }); ```