# Authentication Source: https://docs.joinrefine.io/api-reference/authentication Secure your API requests with proper authentication ## API Key Authentication All Refine API endpoints require authentication using an API key. Include your API key in the request headers: ```bash theme={null} REFINE_API_KEY: your_api_key_here ``` Keep your API key secure and never expose it in client-side code or public repositories. ## API Key Types Refine API keys come with different permission levels: Full access to resources within your organization. Can manage catalogs, products, and access all API endpoints for your organization. Read access to resources within your organization. Can search products and get recommendations but cannot modify catalogs or products. ## Authorization Rules Different endpoints have different authorization requirements. All access is limited to resources within your organization: | Endpoint Type | ADMIN | USER | | ------------------ | ----- | ---- | | Catalog Management | ✓ | ✗ | | Product Management | ✓ | ✗ | | Search | ✓ | ✓ | | Recommendations | ✓ | ✓ | All API keys can only access resources within their own organization. You cannot access another organization's catalogs or products. ## Error Responses Authentication failures will return appropriate HTTP status codes: ### 401 Unauthorized Returned when: * `REFINE_API_KEY` header is missing * API key is invalid * Organization is inactive * Rate limit grace period has expired ```json theme={null} { "status": 401, "message": "Unauthorized", "time": "2024-06-14T19:21:00Z", "method": "GET", "url": "/organizations/a8cd2722-1234-4567-9abc-def123456789/catalogs" } ``` ### 403 Forbidden Returned when: * API key doesn't have permission for the requested resource * Attempting to access resources from a different organization ```json theme={null} { "status": 403, "message": "Forbidden", "time": "2024-06-14T19:21:00Z", "method": "POST", "url": "/organizations/a8cd2722-1234-4567-9abc-def123456789/catalogs" } ``` ## Best Practices Rotate your API keys periodically to maintain security Store API keys in environment variables, not in code Use the minimum permission level required for your use case Track API key usage to detect any unusual activity # Create Catalog Source: https://docs.joinrefine.io/api-reference/catalog-operations/create-catalog POST /organizations/{orgId}/catalogs Create a new catalog for your organization # Delete Catalog Source: https://docs.joinrefine.io/api-reference/catalog-operations/delete-catalog DELETE /organizations/{orgId}/catalogs/{catalogId} Delete a catalog (soft delete) # Get Catalog Source: https://docs.joinrefine.io/api-reference/catalog-operations/get-catalog GET /organizations/{orgId}/catalogs/{catalogId} Get a specific catalog by ID # List Catalogs Source: https://docs.joinrefine.io/api-reference/catalog-operations/list-catalogs GET /organizations/{orgId}/catalogs Get all catalogs for an organization # Update Catalog Source: https://docs.joinrefine.io/api-reference/catalog-operations/update-catalog PUT /organizations/{orgId}/catalogs/{catalogId} Update catalog details # Introduction Source: https://docs.joinrefine.io/api-reference/introduction Welcome to the Refine API documentation ## Overview The Refine API enables you to manage product catalogs and deliver product recommendations and search experiences. Built for e-commerce and retail applications, our API provides powerful visual and text-based search capabilities with real-time product management. ## Base URL All API requests should be made to: ``` https://api.joinrefine.io ``` ## API Overview The Refine API is organized around REST principles and uses standard HTTP methods, authentication, and response codes. All responses are returned in JSON format. ### Core Capabilities Create and manage product catalogs for your organization Add, update, and organize products within your catalogs Search products using text queries with visual similarity matching Get AI-powered product recommendations based on visual similarity ## Getting Started Generate an API key with Admin permissions from the Refine Dashboard > API keys tab Use the Dashboard UI or the API to create a product catalog Upload products with images and metadata to your catalog Use our Search and Recommendations APIs to power your product discovery ## SDKs & Tools **Coming Soon!** We're actively developing our JavaScript SDK to make integration even easier. ## Need Help? Contact our support team for assistance # Create Products Source: https://docs.joinrefine.io/api-reference/product-operations/create-products POST /organizations/{orgId}/catalogs/{catalogId}/products Batch create products in a catalog # Delete Multiple Products Source: https://docs.joinrefine.io/api-reference/product-operations/delete-multiple-products DELETE /organizations/{orgId}/catalogs/{catalogId}/products Delete multiple products or all products in a catalog # Delete Product Source: https://docs.joinrefine.io/api-reference/product-operations/delete-product DELETE /organizations/{orgId}/catalogs/{catalogId}/products/{productId} Delete a single product # Get Product Source: https://docs.joinrefine.io/api-reference/product-operations/get-product GET /organizations/{orgId}/catalogs/{catalogId}/products/{productId} Get a specific product by ID # List Products Source: https://docs.joinrefine.io/api-reference/product-operations/list-products GET /organizations/{orgId}/catalogs/{catalogId}/products Get paginated list of products in a catalog # Update Product Rank Source: https://docs.joinrefine.io/api-reference/product-operations/update-product-rank PUT /organizations/{orgId}/catalogs/{catalogId}/products/{productId}/rank Update the ranking boost of a product # Rate Limits Source: https://docs.joinrefine.io/api-reference/rate-limits Understanding API rate limits and best practices ## Overview The Refine API implements rate limiting to ensure fair usage and maintain service reliability for all users. Rate limits are applied per organization based on your subscription tier. ## Rate Limit Tiers * **100 requests per minute** * **1,000 requests per hour** * **10,000 requests per day** * **1,000 requests per minute** * **30,000 requests per hour** * **500,000 requests per day** * **10,000 requests per minute** * **Custom hourly limits** * **No daily limits** * **Dedicated support** ## Rate Limit Headers Every API response includes headers that show your current rate limit status: ``` X-RateLimit-Limit: 1000 X-RateLimit-Remaining: 999 X-RateLimit-Reset: 1623456789 ``` | Header | Description | | ----------------------- | -------------------------------------------------- | | `X-RateLimit-Limit` | Maximum requests allowed in the current window | | `X-RateLimit-Remaining` | Number of requests remaining in the current window | | `X-RateLimit-Reset` | Unix timestamp when the rate limit window resets | ## Rate Limit Response When you exceed the rate limit, the API returns a `429 Too Many Requests` response: ```json theme={null} { "status": 429, "message": "Rate limit exceeded", "time": "2024-06-14T19:21:00Z", "method": "GET", "url": "/organizations/a8cd2722-1234-4567-9abc-def123456789/catalogs", "retry_after": 30 } ``` ## Grace Period Non-Enterprise subscriptions have a rate limit grace period. If your subscription expires or you exceed your quota, the API will continue to work for a limited time before returning 401 Unauthorized errors. ## Best Practices ### 1. Implement Exponential Backoff When you receive a 429 response, implement exponential backoff: ```python Python theme={null} import time import requests def make_request_with_retry(url, headers, max_retries=3): for attempt in range(max_retries): response = requests.get(url, headers=headers) if response.status_code != 429: return response # Exponential backoff wait_time = 2 ** attempt time.sleep(wait_time) return response ``` ```javascript Node.js theme={null} async function makeRequestWithRetry(url, headers, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { const response = await fetch(url, { headers }); if (response.status !== 429) { return response; } // Exponential backoff const waitTime = Math.pow(2, attempt) * 1000; await new Promise(resolve => setTimeout(resolve, waitTime)); } return response; } ``` ### 2. Cache Responses Reduce API calls by caching responses when appropriate: * Cache catalog listings for 5-10 minutes * Cache product details for 1-5 minutes * Never cache search results or recommendations ### 3. Batch Operations Use batch endpoints when available: * Create multiple products in a single request * Delete multiple products in one operation * Process updates in batches rather than individually ### 4. Monitor Usage Track your API usage to avoid hitting limits: ```python theme={null} remaining = int(response.headers.get('X-RateLimit-Remaining', 0)) if remaining < 100: logger.warning(f"Low rate limit: {remaining} requests remaining") ``` ## Rate Limit Optimization Subscribe to webhooks instead of polling for updates Cache frequently accessed data to reduce API calls Combine multiple operations into single requests Apply filters to reduce response size and processing time ## Need Higher Limits? If you're consistently hitting rate limits, consider: 1. **Upgrading your plan** - Higher tiers offer increased limits 2. **Contacting sales** - Enterprise plans can be customized 3. **Optimizing your integration** - Our team can help identify optimization opportunities Discuss custom rate limits for your use case # Get Recommendations Source: https://docs.joinrefine.io/api-reference/recommendations POST /recs Get product recommendations based on visual similarity # Get Recommendations Source: https://docs.joinrefine.io/api-reference/recommendations/get-recommendations api-reference/openapi.json post /recs Get product recommendations based on visual similarity # Search Products Source: https://docs.joinrefine.io/api-reference/search POST /search Search for products using text queries with visual similarity # Search Products Source: https://docs.joinrefine.io/api-reference/search/search-products api-reference/openapi.json post /search Search for products using text queries with visual similarity # Core Concepts Source: https://docs.joinrefine.io/getting-started/concepts Understanding the fundamentals of Refine ## Visual Search Traditional e-commerce search matches keywords. Refine understands what products *look like*. When you search for "floral midi dress," Refine: 1. **Understands the text** — semantic understanding of "floral," "midi," and "dress" 2. **Analyzes visual features** — patterns, colors, silhouettes from product images 3. **Combines both signals** — the `visualWeight` parameter controls the balance ```typescript theme={null} // Text-heavy search (specs matter more) const results = await refine.search.text({ query: 'laptop 16gb ram', visualWeight: 0.2 // 80% text, 20% visual }); // Visual-heavy search (appearance matters more) const results = await refine.search.text({ query: 'boho summer dress', visualWeight: 0.7 // 30% text, 70% visual }); ``` ## Catalogs A **catalog** is a collection of products that share a search index. Most stores have one catalog, but you might use multiple for: * Separate indexes per locale (US, EU, APAC) * B2B vs B2C product sets * Multiple brands under one organization Each catalog has a unique ID used in SDK initialization: ```typescript theme={null} const refine = new Refine({ catalogId: 'cat_us_retail_2024' }); ``` ## Visual Embeddings When you upload a product, Refine generates a **visual embedding** — a numerical representation of what the product looks like. These embeddings power: * **Visual similarity** — finding products that look alike * **Image search** — matching uploaded photos to your catalog * **Visual weight** — the visual component of text search Embeddings are generated automatically. You don't need to manage them directly. ## Surfaces and Sources When tracking events, you specify **where** the products appeared and **how** they got there. ### Surface The UI location where products are displayed: | Surface | Description | | ---------------- | ----------------------------------- | | `search_results` | Main search results page | | `product_page` | Product detail page recommendations | | `home_page` | Homepage recommendations | | `cart_page` | Cart page cross-sells | | `category_page` | Category/PLP pages | | `checkout` | Checkout page suggestions | ### Source How the products were generated: | Source | Description | | --------------- | ------------------------------- | | `text-search` | Text search results | | `image-search` | Image search results | | `similar-items` | Similar product recommendations | | `visitor-recs` | Visitor-based recommendations | | `user-recs` | User-based recommendations | | `plp` | Product listing page | ```typescript theme={null} const context = refine.events.trackItemsServed({ surface: 'product_page', source: 'similar-items', itemIds: productIds }); ``` ## Identity Hierarchy Refine tracks three levels of identity: Auto-generated, persisted in localStorage. Survives sessions but not device changes. Every user starts as a visitor. Auto-generated per browsing session. Expires after 30 minutes of inactivity (configurable). Your identifier, set via `refine.identify()`. Links visitor behavior to a known user account. ```typescript theme={null} // Anonymous visitor browsing const visitorId = refine.getVisitorId(); // Auto-generated // User logs in refine.identify('user_12345'); // Now visitor history is linked to user_12345 const recs = await refine.recs.forUser({ configId: 'config_abc' }); ``` ## Recommendation Strategies Refine supports three recommendation types: ### Similar Items Find products visually and contextually similar to a specific product. Best for product detail pages. ```typescript theme={null} const recs = await refine.recs.similarItems({ anchorId: 'sku_dress_001', // The product being viewed topK: 8 }); ``` ### Visitor Recommendations Personalized suggestions based on the current visitor's browsing behavior. No login required. ```typescript theme={null} const recs = await refine.recs.forVisitor({ configId: 'homepage_recs', topK: 12 }); ``` ### User Recommendations Deep personalization based on a logged-in user's full history across sessions and devices. ```typescript theme={null} refine.identify('user_12345'); const recs = await refine.recs.forUser({ configId: 'you_may_like', topK: 12 }); ``` ## ServeContext Pattern The SDK uses a **ServeContext** pattern for event tracking. When products are displayed, you get a context object that tracks subsequent interactions: ```typescript theme={null} // Products are served const context = refine.events.trackSearch(query, results.results, options); // User interacts context.trackClick(productId, position); // They clicked context.trackView(productId, position); // It became visible context.trackAddToCart(productId); // They added to cart ``` This pattern ensures all interactions are correctly attributed to the original search or recommendation serve. ## Next Steps Full terminology reference Start building with the SDK # Glossary Source: https://docs.joinrefine.io/getting-started/glossary Terminology and definitions used throughout Refine ## A The product ID used as the reference point for similar item recommendations. In `refine.recs.similarItems({ anchorId: 'sku_001' })`, the anchor is `sku_001`. Authentication credential for the Refine API. Obtained from the dashboard. Keep it secret in production environments. ## C A collection of products that share a search index. Contains product data, images, and visual embeddings. Identified by a unique `catalogId`. Identifier for a recommendation configuration created in the dashboard. Defines which recommendation strategy and parameters to use. A purchase event tracked via `trackPurchase()`. Links back to the original search or recommendation that led to the sale. ## E A numerical vector representation of a product's visual features. Generated automatically when products are ingested. Powers visual similarity matching. A tracked user interaction: impression, click, view, add-to-cart, or purchase. Events power analytics and recommendation improvements. ## F A constraint applied to search or recommendation results. Uses operators like `eq`, `gt`, `in` to match product fields. ```typescript theme={null} { field: 'price', operator: 'lte', value: 100 } ``` Available operators for filters: * `eq` — equals * `ne` — not equals * `gt` / `gte` — greater than / greater than or equal * `lt` / `lte` — less than / less than or equal * `in` / `nin` — in array / not in array * `exists` — field exists * `match` — text matching Force-send all queued events immediately. Called via `refine.events.flush()`. Useful before page unload. ## I Link a visitor to a known user account via `refine.identify('user_id')`. Enables user-based recommendations and cross-session tracking. Search by uploading an image instead of typing text. Finds products visually similar to the uploaded image. When a product is served in search results or recommendations, regardless of whether it was viewed. ## M Custom fields on a product beyond standard fields (title, price, image). Stored as key-value pairs, filterable via `metadata.fieldName`. ## O Unique identifier for your Refine organization. Contains multiple catalogs and users. Required for SDK initialization. ## P A curated collection of products, often used for category pages. Supports pinned products and intelligent ranking. SDK extension that adds functionality. Built-in plugins include `DebugPlugin`, `ConsentPlugin`, and `AutoTrackPlugin`. Zero-indexed location of a product in search results or recommendations. Used in event tracking for click attribution. ## R AI-generated product suggestions. Types include similar items, visitor-based, and user-based recommendations. An error that may succeed if retried. Includes `RefineRateLimitError`, `RefineTimeoutError`, `RefineServerError`, and `RefineNetworkError`. ## S Object returned when tracking served items. Contains methods like `trackClick()`, `trackView()`, and `trackAddToCart()` for subsequent interactions. Unique identifier for a single serve event (search results or recommendations). Links impressions to subsequent interactions. Auto-generated identifier for a browsing session. Expires after 30 minutes of inactivity. Retrieved via `refine.getSessionId()`. Recommendation type that finds products visually and contextually similar to a specified anchor product. How products were generated (e.g., `text-search`, `image-search`, `similar-items`). Used in event tracking. Where products are displayed in the UI (e.g., `search_results`, `product_page`, `home_page`). Used in event tracking. ## T Search using natural language queries. Combines semantic text understanding with visual similarity matching. The number of results to return from a search or recommendation request. Common values: 8-48. The total number of matching products, not limited by `topK`. Useful for pagination UI ("Showing 24 of 1,847 results"). ## V When a product becomes visible to the user (enters the viewport). Tracked via `context.trackView()`. Auto-generated identifier for an anonymous visitor. Persisted in localStorage. Retrieved via `refine.getVisitorId()`. Parameter (0.0-1.0) controlling the balance between text and visual search. `0.0` = pure text, `1.0` = pure visual, `0.3` = default. ## U Your application's identifier for a logged-in user. Set via `refine.identify('user_id')`. Enables personalized recommendations. Personalized suggestions for identified (logged-in) users based on their full history across sessions and devices. # Quickstart Source: https://docs.joinrefine.io/getting-started/quickstart Get Refine search working in your app in 5 minutes ## Prerequisites Before you begin, you'll need: * A Refine account with an API key * An organization ID and catalog ID from your dashboard * A product catalog uploaded to Refine Don't have a catalog yet? See [Creating a Catalog](/api-reference/catalog-operations/create-catalog) to set one up via API, or use the dashboard. ## Install the SDK ```bash npm theme={null} npm install @refine-ai/sdk ``` ```bash yarn theme={null} yarn add @refine-ai/sdk ``` ```bash pnpm theme={null} pnpm add @refine-ai/sdk ``` ## Initialize the Client ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); ``` Never expose your API key in client-side code for production applications. Use environment variables and consider server-side rendering for sensitive operations. ## Make Your First Search ```typescript theme={null} const results = await refine.search.text({ query: 'blue running shoes', topK: 12 }); console.log(`Found ${results.totalResults} products`); results.results.forEach(product => { console.log(`${product.title} - $${product.price}`); }); ``` ## Display Results Here's a complete example rendering search results: ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); async function search(query: string) { const results = await refine.search.text({ query, topK: 24, visualWeight: 0.4 }); // Track the search for analytics const searchContext = refine.events.trackSearch( query, results.results, { surface: 'search_results', totalResults: results.totalResults } ); // Render results const container = document.getElementById('results'); container.innerHTML = results.results.map((product, index) => `
${product.title}

${product.title}

$${product.price}

`).join(''); // Track clicks container.querySelectorAll('.product').forEach(el => { el.addEventListener('click', () => { const productId = el.dataset.id; const position = parseInt(el.dataset.position); searchContext.trackClick(productId, position); }); }); } ``` ## Track Conversions When a user makes a purchase, track the conversion to close the analytics loop: ```typescript theme={null} refine.events.trackPurchase({ orderId: 'order_12345', value: 149.99, currency: 'USD', items: [ { itemId: 'sku_001', quantity: 1, unitPrice: 99.99 }, { itemId: 'sku_002', quantity: 2, unitPrice: 25.00 } ] }); ``` ## What's Next? Advanced text search with filters and sorting Search by uploading images Add product recommendations Complete event tracking guide # Welcome to Refine Source: https://docs.joinrefine.io/getting-started/welcome AI-powered visual search and recommendations for e-commerce ## What is Refine? Refine is an AI-powered search and recommendations platform that helps e-commerce stores deliver relevant product discovery experiences. Our visual AI understands what products look like, enabling natural language search, image-based discovery, and intelligent recommendations. ## Core Capabilities Natural language queries with visual understanding. Search for "red summer dress" and get visually similar results, not just keyword matches. Upload an image to find visually similar products. Perfect for "shop the look" experiences. Similar items, visitor-based, and user-based personalization powered by visual AI and behavioral signals. Curated, merchandised collections with pinned products and intelligent ranking. ## How It Works Upload your product data via API or dashboard. Refine processes images and generates visual embeddings for every product. Add the JavaScript SDK to your storefront. Initialize with your API key and start making search and recommendation requests. Use the built-in event tracking to capture impressions, clicks, and purchases. This data powers analytics and improves recommendations. Use the dashboard to tune visual weights, configure recommendation strategies, and analyze performance. ## Choose Your Path Get search working in 5 minutes Understand the fundamentals Complete SDK documentation REST API documentation ## Need Help? * **Email**: [support@joinrefine.io](mailto:support@joinrefine.io) * **Dashboard**: [app.joinrefine.io](https://app.joinrefine.io) # Configuration Source: https://docs.joinrefine.io/sdk/configuration Complete reference for SDK configuration options ## Full Configuration ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ // Required apiKey: 'your-api-key', organizationId: 'org-uuid', catalogId: 'catalog-uuid', // Optional applicationType: 'web', debug: false, // Event tracking configuration events: { enabled: true, batchSize: 10, flushInterval: 5000, maxQueueSize: 1000, maxRetries: 3, persistence: 'localStorage', sessionTimeout: 30 * 60 * 1000 }, // Privacy configuration privacy: { respectDoNotTrack: false, anonymizeIp: false, requireConsent: false }, // Global error handler onError: (error) => { console.error('Refine error:', error); } }); ``` ## Required Options Your Refine API key. Obtain from Dashboard → Settings → API Keys. Your organization UUID. Find at Dashboard → Settings → Organization. The catalog to search. Find at Dashboard → Catalogs. ## Optional Options Application type identifier. Values: `'web'`, `'mobile'`, `'server'`. Enable debug logging. Logs all requests, responses, and events to the console. Global error handler called for all SDK errors. Useful for centralized error reporting. ## Events Configuration Control how events are batched, stored, and transmitted. ```typescript theme={null} events: { enabled: true, batchSize: 10, flushInterval: 5000, maxQueueSize: 1000, maxRetries: 3, persistence: 'localStorage', sessionTimeout: 30 * 60 * 1000 } ``` Enable or disable event tracking entirely. Number of events to batch before sending. Lower values = more frequent requests but fresher data. Maximum time (ms) between flushes, regardless of batch size. Maximum events to queue. Oldest events are dropped when exceeded. Retry attempts for failed event submissions. Where to persist the event queue. Options: * `'localStorage'` — Survives page refreshes (browser only) * `'sessionStorage'` — Cleared on tab close * `'memory'` — No persistence (lost on refresh) * `'none'` — Disable persistence Session timeout in milliseconds. Default is 30 minutes (30 \* 60 \* 1000). ## Privacy Configuration GDPR and privacy-related options. ```typescript theme={null} privacy: { respectDoNotTrack: false, anonymizeIp: false, requireConsent: false } ``` When `true`, disables tracking if the browser's Do Not Track setting is enabled. When `true`, IP addresses are anonymized before storage. When `true`, event tracking is paused until consent is granted via the ConsentPlugin. ## Configuration Patterns ### Development vs Production ```typescript theme={null} const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: process.env.REFINE_ORG_ID, catalogId: process.env.REFINE_CATALOG_ID, debug: process.env.NODE_ENV === 'development', events: { enabled: process.env.NODE_ENV === 'production', persistence: process.env.NODE_ENV === 'production' ? 'localStorage' : 'memory' } }); ``` ### GDPR Compliance ```typescript theme={null} import { Refine, ConsentPlugin } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', privacy: { respectDoNotTrack: true, anonymizeIp: true, requireConsent: true } }); const consentPlugin = new ConsentPlugin({ required: true, onConsentRequired: () => { showConsentBanner(); } }); refine.use(consentPlugin); // When user grants consent function handleConsentGranted() { consentPlugin.grant(); } ``` ### High-Volume Sites For high-traffic applications, increase batch size and queue limits: ```typescript theme={null} const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', events: { batchSize: 50, flushInterval: 10000, maxQueueSize: 5000, maxRetries: 5 } }); ``` ### Server-Side Rendering For SSR environments where localStorage isn't available: ```typescript theme={null} const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', applicationType: 'server', events: { persistence: 'memory' } }); ``` ## Updating Configuration The SDK doesn't support runtime configuration changes. Create a new instance if you need different settings: ```typescript theme={null} // Don't do this refine.config.debug = true; // ❌ Won't work // Do this instead const debugRefine = new Refine({ ...baseConfig, debug: true }); ``` ## Next Steps Start searching Extend SDK functionality # Error Handling Source: https://docs.joinrefine.io/sdk/error-handling Handle errors gracefully with typed error classes and retry strategies ## Overview The SDK provides typed error classes for different failure scenarios. Some errors are retryable (network issues, rate limits), while others require code changes (validation, auth). ## Error Types | Error Class | Status Code | Retryable | Cause | | ----------------------- | ------------- | --------- | -------------------------- | | `RefineValidationError` | 400 | No | Invalid request parameters | | `RefineAuthError` | 401 | No | Invalid or missing API key | | `RefineForbiddenError` | 403 | No | Insufficient permissions | | `RefineNotFoundError` | 404 | No | Resource doesn't exist | | `RefineRateLimitError` | 429 | Yes | Too many requests | | `RefineTimeoutError` | 408, 504 | Yes | Request timed out | | `RefineServerError` | 500, 502, 503 | Yes | Server-side issue | | `RefineNetworkError` | - | Yes | Network connectivity issue | ## Basic Error Handling ```typescript theme={null} import { Refine, RefineValidationError, RefineAuthError, RefineNotFoundError, RefineRateLimitError, RefineServerError, RefineNetworkError } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); try { const results = await refine.search.text({ query: 'summer dress', topK: 24 }); } catch (error) { if (error instanceof RefineValidationError) { // Bad request - fix the parameters console.error('Invalid parameters:', error.message); } else if (error instanceof RefineAuthError) { // Auth issue - check API key console.error('Authentication failed:', error.message); } else if (error instanceof RefineNotFoundError) { // Resource not found console.error('Not found:', error.message); } else if (error instanceof RefineRateLimitError) { // Rate limited - wait and retry console.error(`Rate limited. Retry after ${error.retryAfter}ms`); } else if (error instanceof RefineServerError) { // Server error - retry with backoff console.error('Server error:', error.message); } else if (error instanceof RefineNetworkError) { // Network issue - check connectivity console.error('Network error:', error.message); } else { // Unknown error throw error; } } ``` ## Error Properties All Refine errors extend `RefineError` and include: ```typescript theme={null} interface RefineError extends Error { name: string; // Error class name message: string; // Human-readable message statusCode?: number; // HTTP status code retryable: boolean; // Whether retry might succeed retryAfter?: number; // Suggested retry delay (ms) requestId?: string; // Request ID for support } ``` ## Retry Strategies For retryable errors, implement exponential backoff: ```typescript theme={null} async function searchWithRetry( query: string, maxRetries: number = 3 ): Promise { let lastError: Error; for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await refine.search.text({ query, topK: 24 }); } catch (error) { lastError = error; if (error instanceof RefineRateLimitError) { // Use server-provided retry delay await sleep(error.retryAfter || 1000); } else if ( error instanceof RefineServerError || error instanceof RefineTimeoutError || error instanceof RefineNetworkError ) { // Exponential backoff await sleep(Math.pow(2, attempt) * 1000); } else { // Non-retryable error throw error; } } } throw lastError; } function sleep(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } ``` ## Global Error Handler Set a global error handler in configuration: ```typescript theme={null} const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', onError: (error) => { // Log to error tracking service errorTracker.capture(error, { requestId: error.requestId, statusCode: error.statusCode }); // Show user-friendly message if (error.retryable) { showNotification('Temporary issue. Please try again.'); } else { showNotification('Something went wrong. Please contact support.'); } } }); ``` ## Error Handling by Feature ### Search ```typescript theme={null} async function performSearch(query: string) { try { return await refine.search.text({ query, topK: 24 }); } catch (error) { if (error instanceof RefineValidationError) { // Query too short, invalid filters, etc. return { results: [], error: 'Invalid search query' }; } if (error.retryable) { // Show loading state and retry return await searchWithRetry(query); } // Non-retryable error return { results: [], error: 'Search unavailable' }; } } ``` ### Recommendations ```typescript theme={null} async function getSimilarItems(productId: string) { try { return await refine.recs.similarItems({ anchorId: productId, topK: 8 }); } catch (error) { if (error instanceof RefineNotFoundError) { // Product not in catalog - fall back to popular items return await refine.recs.forVisitor({ configId: 'popular', topK: 8 }); } if (error.retryable) { // Retry once await sleep(1000); return await refine.recs.similarItems({ anchorId: productId, topK: 8 }); } // Return empty recommendations return { results: [] }; } } ``` ### Event Tracking Event tracking is designed to be fire-and-forget, but you can handle errors: ```typescript theme={null} try { refine.events.trackPurchase({ orderId: 'order_123', value: 99.99, currency: 'USD', items: [{ itemId: 'sku_001', quantity: 1, unitPrice: 99.99 }] }); } catch (error) { // Events are queued, so errors here are rare console.error('Failed to queue event:', error); } // Flush errors try { await refine.events.flush(); } catch (error) { if (error instanceof RefineNetworkError) { // Events will be retried automatically console.warn('Events queued for retry'); } } ``` ## User-Facing Error Messages Map errors to user-friendly messages: ```typescript theme={null} function getUserMessage(error: RefineError): string { if (error instanceof RefineValidationError) { return 'Please check your search query and try again.'; } if (error instanceof RefineRateLimitError) { return 'Too many requests. Please wait a moment.'; } if (error instanceof RefineNetworkError) { return 'Connection issue. Check your internet and try again.'; } if (error.retryable) { return 'Temporary issue. Please try again.'; } return 'Something went wrong. Please try again later.'; } ``` ## Debugging Errors Enable debug mode for detailed error information: ```typescript theme={null} const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', debug: true }); // Errors will include: // - Full request/response details // - Request ID for support // - Stack trace ``` ## Error Monitoring Integration Integrate with error monitoring services: ```typescript theme={null} import * as Sentry from '@sentry/browser'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', onError: (error) => { Sentry.captureException(error, { tags: { refine_error: error.name, retryable: error.retryable, status_code: error.statusCode }, extra: { request_id: error.requestId } }); } }); ``` ## Handling Specific Scenarios ### Rate Limiting ```typescript theme={null} import { RefineRateLimitError } from '@refine-ai/sdk'; async function handleRateLimit( operation: () => Promise ): Promise { try { return await operation(); } catch (error) { if (error instanceof RefineRateLimitError) { // Show user feedback showNotification(`Please wait ${Math.ceil(error.retryAfter / 1000)} seconds`); // Wait and retry once await sleep(error.retryAfter); return await operation(); } throw error; } } // Usage const results = await handleRateLimit(() => refine.search.text({ query: 'shoes', topK: 24 }) ); ``` ### Network Offline ```typescript theme={null} import { RefineNetworkError } from '@refine-ai/sdk'; async function searchWithOfflineSupport(query: string) { try { return await refine.search.text({ query, topK: 24 }); } catch (error) { if (error instanceof RefineNetworkError) { // Check if actually offline if (!navigator.onLine) { showNotification('You appear to be offline'); return getCachedResults(query); } // Online but network error - retry await sleep(2000); return await refine.search.text({ query, topK: 24 }); } throw error; } } ``` ## Next Steps Configure error handling globally Debug errors in development # Conversion Tracking Source: https://docs.joinrefine.io/sdk/events/conversion-tracking Track purchases and attribute conversions to search and recommendations ## Overview Conversion tracking links purchases back to the search queries and recommendations that drove them. This data powers revenue attribution reporting and improves recommendation models. ## Tracking Purchases Call `trackPurchase` when an order is completed: ```typescript theme={null} refine.events.trackPurchase({ orderId: 'order_12345', value: 249.97, currency: 'USD', items: [ { itemId: 'sku_001', quantity: 1, unitPrice: 149.99 }, { itemId: 'sku_002', quantity: 2, unitPrice: 49.99 } ] }); ``` ## Purchase Parameters Unique identifier for the order. Used for deduplication. Total order value (sum of all items). ISO 4217 currency code (e.g., 'USD', 'EUR', 'GBP'). Array of purchased items. ### PurchaseItem Product ID matching your catalog. Number of units purchased. Price per unit at time of purchase. ## Attribution Refine automatically attributes purchases to previous interactions within the attribution window (default: 7 days). The flow: 1. User searches for "running shoes" 2. User clicks on product SKU\_001 3. User adds SKU\_001 to cart 4. User completes purchase with SKU\_001 The purchase is attributed to the original search. Attribution works automatically using the visitor/user ID. You don't need to pass the original serve ID to `trackPurchase`. ## Implementation Examples ### Order Confirmation Page ```typescript theme={null} // On order confirmation page async function trackOrderComplete(order: Order) { refine.events.trackPurchase({ orderId: order.id, value: order.total, currency: order.currency, items: order.lineItems.map(item => ({ itemId: item.productId, quantity: item.quantity, unitPrice: item.price })) }); // Ensure event is sent before user navigates away await refine.events.flush(); } ``` ### E-commerce Platform Integration ```typescript theme={null} // In your Shopify checkout extension or theme document.addEventListener('DOMContentLoaded', () => { // Check if on thank you page if (window.Shopify?.checkout?.order_id) { const checkout = window.Shopify.checkout; refine.events.trackPurchase({ orderId: checkout.order_id.toString(), value: parseFloat(checkout.total_price), currency: checkout.currency, items: checkout.line_items.map(item => ({ itemId: item.sku || item.variant_id.toString(), quantity: item.quantity, unitPrice: parseFloat(item.price) })) }); } }); ``` ```typescript theme={null} // In your theme or custom plugin jQuery(document).ready(function($) { if ($('body').hasClass('woocommerce-order-received')) { const orderData = window.woocommerce_order_data; refine.events.trackPurchase({ orderId: orderData.order_id, value: orderData.total, currency: orderData.currency, items: orderData.items.map(item => ({ itemId: item.sku, quantity: item.quantity, unitPrice: item.price })) }); } }); ``` ```typescript theme={null} // Server-side tracking (Node.js) import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', applicationType: 'server' }); async function handleOrderComplete(order: Order, userId: string) { // Identify the user who made the purchase refine.identify(userId); refine.events.trackPurchase({ orderId: order.id, value: order.total, currency: order.currency, items: order.items.map(item => ({ itemId: item.productId, quantity: item.quantity, unitPrice: item.unitPrice })) }); await refine.events.flush(); } ``` ## Handling Edge Cases ### Duplicate Prevention Refine deduplicates purchases by `orderId`. If the same order is tracked multiple times, only the first is recorded. ```typescript theme={null} // Safe to call multiple times with same orderId refine.events.trackPurchase({ orderId: 'order_123', ... }); refine.events.trackPurchase({ orderId: 'order_123', ... }); // Ignored ``` ### Partial Orders Track only the items that were actually fulfilled: ```typescript theme={null} // Original order had 3 items, but 1 was out of stock refine.events.trackPurchase({ orderId: 'order_123', value: 199.98, // Adjusted total currency: 'USD', items: [ { itemId: 'sku_001', quantity: 1, unitPrice: 149.99 }, { itemId: 'sku_002', quantity: 1, unitPrice: 49.99 } // sku_003 excluded - out of stock ] }); ``` ### Refunds For full refunds, no action needed (attribution is preserved for analytics). For partial refunds, you may optionally track a negative adjustment: ```typescript theme={null} // Optional: Track refund for analytics refine.events.trackPurchase({ orderId: 'refund_order_123', value: -49.99, currency: 'USD', items: [ { itemId: 'sku_002', quantity: -1, unitPrice: 49.99 } ] }); ``` ### Guest Checkout For guest checkout, the visitor ID automatically links the purchase to previous interactions: ```typescript theme={null} // No identify() needed - visitor ID handles attribution refine.events.trackPurchase({ orderId: 'order_guest_456', value: 99.99, currency: 'USD', items: [{ itemId: 'sku_001', quantity: 1, unitPrice: 99.99 }] }); ``` ### Post-Purchase Identification If the user creates an account after checkout, call identify to link: ```typescript theme={null} // User completes purchase as guest refine.events.trackPurchase({ orderId: 'order_123', ... }); // Later, user creates account refine.identify('new_user_789'); // Future purchases and browsing now linked to user account ``` ## Ensuring Data Delivery Always flush events after tracking purchases: ```typescript theme={null} async function onOrderComplete(order: Order) { refine.events.trackPurchase({ orderId: order.id, value: order.total, currency: order.currency, items: order.items }); // Wait for event to be sent await refine.events.flush(); // Now safe to redirect window.location.href = '/order-confirmation'; } ``` ### Beacon API Fallback For page unloads, the SDK uses the Beacon API when available: ```typescript theme={null} window.addEventListener('beforeunload', () => { // SDK handles Beacon API internally during flush refine.events.flush(); }); ``` ## Testing Conversions Enable debug mode to verify purchase tracking: ```typescript theme={null} const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', debug: true // Logs all events to console }); // Track a test purchase refine.events.trackPurchase({ orderId: 'test_order_001', value: 99.99, currency: 'USD', items: [{ itemId: 'sku_test', quantity: 1, unitPrice: 99.99 }] }); // Check console for: // [Refine] trackPurchase { orderId: 'test_order_001', ... } ``` ## Next Steps Complete event tracking guide View conversion reports # Event Tracking Overview Source: https://docs.joinrefine.io/sdk/events/overview Track user interactions to power analytics and improve recommendations ## Overview Event tracking captures user interactions—impressions, clicks, views, adds-to-cart, and purchases. This data powers: * **Analytics**: Understand how users interact with search and recommendations * **Attribution**: Link sales back to the search or recommendation that drove them * **Model Improvement**: Feedback loops that improve recommendations over time ## The ServeContext Pattern When products are displayed, you create a **ServeContext** that tracks subsequent interactions: ```typescript theme={null} // Products are served const context = refine.events.trackSearch(query, results, options); // User interacts context.trackClick(productId, position); // They clicked context.trackView(productId, position); // It became visible context.trackAddToCart(productId); // They added to cart ``` This pattern ensures all interactions are correctly attributed to the original serve event. ## Quick Start ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); // Search and track const results = await refine.search.text({ query: 'shoes', topK: 20 }); const searchContext = refine.events.trackSearch( 'shoes', results.results, { surface: 'search_results', totalResults: results.totalResults } ); // Track clicks function handleProductClick(productId: string, position: number) { searchContext.trackClick(productId, position); } // Track purchase (separate from serve context) refine.events.trackPurchase({ orderId: 'order_123', value: 149.99, currency: 'USD', items: [{ itemId: 'sku_001', quantity: 1, unitPrice: 149.99 }] }); ``` ## Event Types | Event | Method | When to Track | | ---------------- | ----------------------------------------------------------------- | ------------------------------------------------- | | **Items Served** | `trackItemsServed()` / `trackSearch()` / `trackRecommendations()` | Products displayed to user | | **Click** | `context.trackClick()` | User clicks a product | | **View** | `context.trackView()` | Product becomes visible (50%+ in viewport for 1s) | | **Add to Cart** | `context.trackAddToCart()` | User adds product to cart | | **Purchase** | `trackPurchase()` | Order completed | ## Tracking Methods ### trackSearch() Convenience method for search results: ```typescript theme={null} const searchContext = refine.events.trackSearch( query, // The search query results.results, // Array of products { surface: 'search_results', totalResults: results.totalResults } ); ``` ### trackRecommendations() Convenience method for recommendation results: ```typescript theme={null} const recsContext = refine.events.trackRecommendations( recs.serveId, // From recommendation response recs.results, // Array of products 'product_page', // Surface 'similar-items', // Source { anchorId: 'sku_001' } // Optional metadata ); ``` ### trackItemsServed() Low-level method for custom scenarios: ```typescript theme={null} const context = refine.events.trackItemsServed({ surface: 'home_page', source: 'curated', itemIds: ['sku_001', 'sku_002', 'sku_003'], totalResults: 3 }); ``` ### trackPurchase() Track completed purchases: ```typescript theme={null} refine.events.trackPurchase({ orderId: 'order_12345', value: 299.98, currency: 'USD', items: [ { itemId: 'sku_001', quantity: 1, unitPrice: 199.99 }, { itemId: 'sku_002', quantity: 2, unitPrice: 49.99 } ] }); ``` ## ServeContext Methods After calling a track method, you get a context with these methods: ```typescript theme={null} const context = refine.events.trackSearch(query, results, options); // User clicked product at position 3 context.trackClick('sku_001', 3); // Product became visible at position 0 context.trackView('sku_001', 0); // User added product to cart context.trackAddToCart('sku_001'); ``` Track when a user clicks on a product. `position` is the 0-indexed position in the results. Track when a product becomes visible. Call when 50%+ of the product is visible for 1+ second. Track when a user adds a product to their cart from this serve context. ## Event Queue Management Events are automatically batched and sent. You can control this behavior: ```typescript theme={null} // Force send all queued events immediately await refine.events.flush(); // Pause event sending (e.g., when offline) refine.events.pause(); // Resume event sending refine.events.resume(); // Get queue metrics const metrics = refine.events.getMetrics(); console.log(metrics); // { queued: 5, sent: 142, failed: 0, retrying: 0 } ``` ## Configuration Control batching, persistence, and retries in SDK initialization: ```typescript theme={null} const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', events: { enabled: true, batchSize: 10, // Events per batch flushInterval: 5000, // Max ms between sends maxQueueSize: 1000, // Max events to queue maxRetries: 3, // Retry attempts persistence: 'localStorage', // Queue storage sessionTimeout: 30 * 60 * 1000 // Session length } }); ``` ## Page Unload Handling Ensure events are sent before the user leaves: ```typescript theme={null} // Modern approach (recommended) document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') { refine.events.flush(); } }); // Fallback for older browsers window.addEventListener('beforeunload', () => { refine.events.flush(); }); ``` ## Complete Example ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); class SearchPage { private searchContext: any; async search(query: string) { const results = await refine.search.text({ query, topK: 24 }); // Track the search this.searchContext = refine.events.trackSearch(query, results.results, { surface: 'search_results', totalResults: results.totalResults }); this.renderResults(results.results); this.setupViewabilityTracking(); return results; } private renderResults(products: any[]) { const container = document.getElementById('results')!; container.innerHTML = products.map((product, index) => `
${product.title}

${product.title}

$${product.price}

`).join(''); // Click handlers container.querySelectorAll('.product').forEach(el => { const productId = (el as HTMLElement).dataset.id!; const position = parseInt((el as HTMLElement).dataset.position!); el.addEventListener('click', (e) => { if ((e.target as HTMLElement).classList.contains('add-to-cart')) { this.searchContext?.trackAddToCart(productId); } else { this.searchContext?.trackClick(productId, position); } }); }); } private setupViewabilityTracking() { const observer = new IntersectionObserver( (entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const el = entry.target as HTMLElement; const productId = el.dataset.id!; const position = parseInt(el.dataset.position!); // Track view after 1 second of visibility setTimeout(() => { if (entry.isIntersecting) { this.searchContext?.trackView(productId, position); observer.unobserve(el); } }, 1000); } }); }, { threshold: 0.5 } ); document.querySelectorAll('.product').forEach(el => { observer.observe(el); }); } } ``` ## Next Steps Detailed tracking implementation Purchase and conversion attribution Automatic event tracking # Tracking Events Source: https://docs.joinrefine.io/sdk/events/tracking-events Implement impression, click, and view tracking for search and recommendations ## Overview Tracking events at each stage of the user journey—from seeing products to clicking them—provides the data needed for analytics and recommendation improvements. ## Event Flow ``` Search/Recs Request → Items Served → User Sees (View) → User Clicks → Add to Cart → Purchase ``` Each event builds on the previous, creating a complete picture of user behavior. ## Tracking Search Results ### Basic Implementation ```typescript theme={null} const results = await refine.search.text({ query: 'summer dress', topK: 24 }); const searchContext = refine.events.trackSearch( 'summer dress', results.results, { surface: 'search_results', totalResults: results.totalResults } ); ``` ### Full Parameters ```typescript theme={null} const searchContext = refine.events.trackSearch( query: string, products: SearchResultItem[], options: { surface: string; // Where products are displayed totalResults: number; // Total matching products filters?: Filter[]; // Applied filters sortBy?: SortBy; // Applied sorting } ); ``` ## Tracking Recommendations ```typescript theme={null} const recs = await refine.recs.similarItems({ anchorId: 'sku_001', topK: 8 }); const recsContext = refine.events.trackRecommendations( recs.serveId, recs.results, 'product_page', // surface 'similar-items', // source { anchorId: 'sku_001' } // metadata ); ``` ## Tracking Clicks Track when a user clicks on a product: ```typescript theme={null} // Basic click tracking searchContext.trackClick(productId, position); // Example with event handler document.querySelectorAll('.product').forEach((el, index) => { el.addEventListener('click', () => { const productId = el.dataset.id; searchContext.trackClick(productId, index); }); }); ``` The `position` parameter is 0-indexed and represents where the product appeared in the results. This is crucial for understanding if users click items at position 1 vs position 20. ## Tracking Views (Viewability) Track when a product becomes visible to the user. Standard viewability requires: * At least 50% of the product visible * Visible for at least 1 second ### Using Intersection Observer ```typescript theme={null} function setupViewabilityTracking(context: ServeContext) { const viewedProducts = new Set(); const observer = new IntersectionObserver( (entries) => { entries.forEach(entry => { const el = entry.target as HTMLElement; const productId = el.dataset.id!; const position = parseInt(el.dataset.position!); if (entry.isIntersecting && !viewedProducts.has(productId)) { // Start 1-second timer const timeout = setTimeout(() => { // Check if still visible const rect = el.getBoundingClientRect(); const isStillVisible = ( rect.top < window.innerHeight && rect.bottom > 0 ); if (isStillVisible) { context.trackView(productId, position); viewedProducts.add(productId); observer.unobserve(el); } }, 1000); // Store timeout to clear if element leaves viewport el.dataset.viewTimeout = String(timeout); } else if (!entry.isIntersecting) { // Clear timeout if element leaves viewport before 1s const timeout = el.dataset.viewTimeout; if (timeout) { clearTimeout(parseInt(timeout)); } } }); }, { threshold: 0.5 } ); document.querySelectorAll('[data-id]').forEach(el => { observer.observe(el); }); return observer; } ``` ### Using Auto Track Plugin For simpler implementation, use the AutoTrackPlugin: ```typescript theme={null} import { AutoTrackPlugin } from '@refine-ai/sdk'; refine.use(new AutoTrackPlugin({ viewability: { enabled: true, threshold: 0.5, // 50% visible duration: 1000 // 1 second } })); ``` See [Auto Track Plugin](/sdk/plugins/auto-track-plugin) for details. ## Tracking Add to Cart Track when a user adds a product to their cart: ```typescript theme={null} // From within a serve context searchContext.trackAddToCart(productId); // Example implementation document.querySelectorAll('.add-to-cart-btn').forEach(btn => { btn.addEventListener('click', (e) => { e.stopPropagation(); const productId = btn.closest('[data-id]').dataset.id; // Track the event searchContext.trackAddToCart(productId); // Actually add to cart addToCart(productId); }); }); ``` ## Low-Level Tracking For custom scenarios, use `trackItemsServed` directly: ```typescript theme={null} const context = refine.events.trackItemsServed({ surface: 'custom_carousel', source: 'editorial-picks', itemIds: ['sku_001', 'sku_002', 'sku_003'], query: null, totalResults: 3, metadata: { carouselName: 'Summer Collection', placement: 'homepage-hero' } }); ``` ### Parameters Where products are displayed. Common values: `search_results`, `product_page`, `home_page`, `category_page`, `cart_page`. How products were generated. Values: `text-search`, `image-search`, `similar-items`, `visitor-recs`, `user-recs`, `plp`, `curated`. Array of product IDs being served. The search query, if applicable. Total available results before pagination. Custom key-value pairs for additional context. ## Complete Page Implementation ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); class ProductGridTracker { private context: any; private observer: IntersectionObserver | null = null; private viewedProducts = new Set(); async loadSearchResults(query: string) { const results = await refine.search.text({ query, topK: 24 }); this.context = refine.events.trackSearch(query, results.results, { surface: 'search_results', totalResults: results.totalResults }); this.render(results.results); this.setupTracking(); return results; } async loadRecommendations(anchorId: string) { const recs = await refine.recs.similarItems({ anchorId, topK: 8 }); this.context = refine.events.trackRecommendations( recs.serveId, recs.results, 'product_page', 'similar-items', { anchorId } ); this.render(recs.results); this.setupTracking(); return recs; } private render(products: any[]) { const container = document.getElementById('products')!; container.innerHTML = products.map((p, i) => `
${p.title}

${p.title}

$${p.price.toFixed(2)}

`).join(''); } private setupTracking() { this.setupClickTracking(); this.setupViewabilityTracking(); } private setupClickTracking() { document.querySelectorAll('.product-card').forEach(card => { const productId = (card as HTMLElement).dataset.id!; const position = parseInt((card as HTMLElement).dataset.position!); // Product click card.addEventListener('click', (e) => { const target = e.target as HTMLElement; if (target.classList.contains('add-to-cart')) { this.context?.trackAddToCart(productId); this.handleAddToCart(productId); } else { this.context?.trackClick(productId, position); this.navigateToProduct(productId); } }); }); } private setupViewabilityTracking() { // Clean up previous observer this.observer?.disconnect(); this.viewedProducts.clear(); this.observer = new IntersectionObserver( (entries) => { entries.forEach(entry => { if (!entry.isIntersecting) return; const el = entry.target as HTMLElement; const productId = el.dataset.id!; const position = parseInt(el.dataset.position!); if (this.viewedProducts.has(productId)) return; // Delay to ensure genuine view setTimeout(() => { if (this.isElementVisible(el) && !this.viewedProducts.has(productId)) { this.context?.trackView(productId, position); this.viewedProducts.add(productId); this.observer?.unobserve(el); } }, 1000); }); }, { threshold: 0.5 } ); document.querySelectorAll('.product-card').forEach(card => { this.observer!.observe(card); }); } private isElementVisible(el: Element): boolean { const rect = el.getBoundingClientRect(); return rect.top < window.innerHeight && rect.bottom > 0; } private handleAddToCart(productId: string) { // Your add to cart logic } private navigateToProduct(productId: string) { window.location.href = `/products/${productId}`; } destroy() { this.observer?.disconnect(); } } // Usage const tracker = new ProductGridTracker(); await tracker.loadSearchResults('summer dress'); ``` ## Best Practices **Do:** * Track clicks immediately on click, not on navigation complete * Track views with a 1-second delay to filter accidental scrolls * Track add-to-cart before the actual cart operation * Use consistent surface and source values across your app **Don't:** * Track views on render (before user could actually see them) * Track clicks multiple times for the same interaction * Forget to track interactions from keyboard navigation * Block user interactions while waiting for tracking to complete ## Next Steps Track purchases and attribution Automatic event tracking # Identity Management Source: https://docs.joinrefine.io/sdk/identity/overview Manage visitor, session, and user identity for personalization and tracking ## Overview Refine tracks three levels of identity to power personalization and analytics: | Level | Persistence | Identifier | | ----------- | ---------------------- | -------------- | | **Visitor** | Browser (localStorage) | Auto-generated | | **Session** | Tab lifetime + timeout | Auto-generated | | **User** | Cross-device | Your user ID | ## Identity Hierarchy ``` ┌─────────────┐ │ User ID │ ← Your identifier (login) │ (optional) │ └──────┬──────┘ │ ┌──────▼──────┐ │ Visitor ID │ ← Auto-generated, persisted │ (required) │ in localStorage └──────┬──────┘ │ ┌──────▼──────┐ │ Session ID │ ← Auto-generated per session │ (required) │ 30 min timeout └─────────────┘ ``` ## Visitor ID Automatically generated on first SDK use and stored in localStorage. ```typescript theme={null} // Get current visitor ID const visitorId = refine.getVisitorId(); console.log(visitorId); // e.g., "v_a1b2c3d4e5f6" ``` **Characteristics:** * Generated once per browser/device * Persists across sessions (survives page refresh, browser close) * Does not persist across devices or browsers * Used for visitor-based recommendations In incognito/private mode, visitor IDs are cleared when the browser closes. ## Session ID Automatically generated for each browsing session. ```typescript theme={null} // Get current session ID const sessionId = refine.getSessionId(); console.log(sessionId); // e.g., "s_x9y8z7w6v5" ``` **Characteristics:** * Generated when SDK initializes * Expires after 30 minutes of inactivity (configurable) * New session created after timeout * Used to group interactions within a visit ### Configure Session Timeout ```typescript theme={null} const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', events: { sessionTimeout: 60 * 60 * 1000 // 1 hour instead of 30 minutes } }); ``` ## User ID Your application's identifier for logged-in users. Set via `identify()`. ```typescript theme={null} // When user logs in refine.identify('user_12345'); // Get current user ID const userId = refine.getUserId(); console.log(userId); // "user_12345" ``` **Characteristics:** * Set by your application * Links visitor behavior to a known user * Enables cross-device personalization * Required for user-based recommendations ## The identify() Method Call `identify()` when a user logs in: ```typescript theme={null} // After successful login async function handleLogin(credentials: Credentials) { const user = await authenticateUser(credentials); // Link visitor to user refine.identify(user.id); // Now user recommendations are available const recs = await refine.recs.forUser({ configId: 'personalized', topK: 12 }); } ``` ### Identity Merging When you call `identify()`, Refine links the current visitor's browsing history to the user account: ```typescript theme={null} // Anonymous visitor browses products await refine.search.text({ query: 'running shoes', topK: 20 }); // Interactions tracked under visitor_abc123 // User logs in refine.identify('user_789'); // Previous visitor_abc123 interactions now linked to user_789 // Future interactions tracked under user_789 await refine.search.text({ query: 'trail shoes', topK: 20 }); ``` ## The reset() Method Call `reset()` when a user logs out: ```typescript theme={null} function handleLogout() { // Clear user identity refine.reset(); // User is now back to anonymous visitor // A new visitor ID will be generated } ``` **What reset() does:** * Clears the user ID * Generates a new visitor ID * Generates a new session ID * Clears any cached personalization After `reset()`, previous browsing behavior is no longer linked to subsequent sessions. Call this on logout to preserve user privacy. ## Identity in Events All events automatically include identity information: ```typescript theme={null} // Event payload (internal) { visitorId: "v_abc123", sessionId: "s_xyz789", userId: "user_12345", // null if not identified event: "click", ... } ``` ## Complete Authentication Flow ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); class AuthManager { async init() { // Check for existing auth const user = await this.getStoredUser(); if (user) { refine.identify(user.id); } } async login(email: string, password: string) { const user = await api.login(email, password); // Link visitor to user refine.identify(user.id); // Store auth this.storeUser(user); return user; } async logout() { await api.logout(); // Clear Refine identity refine.reset(); // Clear stored auth this.clearStoredUser(); } private async getStoredUser() { // Your auth storage logic } private storeUser(user: User) { // Your auth storage logic } private clearStoredUser() { // Your auth storage logic } } // Usage const auth = new AuthManager(); await auth.init(); // Get appropriate recommendations async function getRecommendations() { if (refine.getUserId()) { // Logged in - use user recommendations return refine.recs.forUser({ configId: 'user_picks', topK: 12 }); } else { // Anonymous - use visitor recommendations return refine.recs.forVisitor({ configId: 'visitor_picks', topK: 12 }); } } ``` ## Server-Side Identity For server-side rendering or API routes, pass identity explicitly: ```typescript theme={null} // Server-side (e.g., Next.js API route) import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', applicationType: 'server' }); export async function getServerSideProps(context) { const userId = context.req.session?.userId; if (userId) { refine.identify(userId); const recs = await refine.recs.forUser({ configId: 'personalized', topK: 12 }); return { props: { recommendations: recs.results } }; } // For anonymous users, use visitor recommendations on client return { props: { recommendations: [] } }; } ``` ## Privacy Considerations ### GDPR Compliance ```typescript theme={null} const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', privacy: { respectDoNotTrack: true, // Honor browser DNT setting anonymizeIp: true, // Anonymize IP addresses requireConsent: true // Wait for consent before tracking } }); ``` ### Data Deletion When a user requests data deletion: 1. Call `refine.reset()` on their device 2. Contact Refine support for server-side deletion ## Debugging Identity ```typescript theme={null} const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', debug: true }); // Check current identity console.log('Visitor:', refine.getVisitorId()); console.log('Session:', refine.getSessionId()); console.log('User:', refine.getUserId()); // After identify refine.identify('user_123'); console.log('User after identify:', refine.getUserId()); // 'user_123' // After reset refine.reset(); console.log('User after reset:', refine.getUserId()); // null console.log('Visitor after reset:', refine.getVisitorId()); // New ID ``` ## Next Steps Personalization for logged-in users GDPR-compliant consent management # Installation Source: https://docs.joinrefine.io/sdk/installation Install the Refine SDK in your project ## Package Installation ```bash npm theme={null} npm install @refine-ai/sdk ``` ```bash yarn theme={null} yarn add @refine-ai/sdk ``` ```bash pnpm theme={null} pnpm add @refine-ai/sdk ``` ## Basic Setup ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); ``` ## Credentials You'll need three credentials from your Refine dashboard: | Credential | Description | Where to Find | | ---------------- | ---------------------- | ------------------------------------- | | `apiKey` | Authentication key | Dashboard → Settings → API Keys | | `organizationId` | Your organization UUID | Dashboard → Settings → Organization | | `catalogId` | Target catalog UUID | Dashboard → Catalogs → Select Catalog | Never expose your API key in client-side code for production. Use environment variables and server-side rendering for sensitive operations. ## Environment Variables ### Next.js ```bash title=".env.local" theme={null} REFINE_API_KEY=your_api_key_here NEXT_PUBLIC_REFINE_ORG_ID=org_abc123 NEXT_PUBLIC_REFINE_CATALOG_ID=cat_xyz789 ``` ```typescript title="lib/refine.ts" theme={null} import { Refine } from '@refine-ai/sdk'; export const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: process.env.NEXT_PUBLIC_REFINE_ORG_ID, catalogId: process.env.NEXT_PUBLIC_REFINE_CATALOG_ID }); ``` ### Vite ```bash title=".env" theme={null} VITE_REFINE_API_KEY=your_api_key_here VITE_REFINE_ORG_ID=org_abc123 VITE_REFINE_CATALOG_ID=cat_xyz789 ``` ```typescript title="src/lib/refine.ts" theme={null} import { Refine } from '@refine-ai/sdk'; export const refine = new Refine({ apiKey: import.meta.env.VITE_REFINE_API_KEY, organizationId: import.meta.env.VITE_REFINE_ORG_ID, catalogId: import.meta.env.VITE_REFINE_CATALOG_ID }); ``` ## TypeScript Support The SDK is written in TypeScript and includes full type definitions. No additional `@types` packages are needed. ```typescript theme={null} import { Refine, SearchResponse, RecommendationResponse, RefineValidationError } from '@refine-ai/sdk'; const results: SearchResponse = await refine.search.text({ query: 'shoes', topK: 20 }); ``` ## Singleton Pattern For most applications, create a single SDK instance and export it: ```typescript title="lib/refine.ts" theme={null} import { Refine } from '@refine-ai/sdk'; export const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); ``` ```typescript title="pages/search.tsx" theme={null} import { refine } from '@/lib/refine'; const results = await refine.search.text({ query, topK: 24 }); ``` ## CDN Usage For non-bundled environments, load directly via CDN: ```html theme={null} ``` CDN usage exposes your API key. Only use this for prototyping or internal tools. ## Verify Installation Test your setup: ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', debug: true // Enables console logging }); // This should log request details and return results const results = await refine.search.text({ query: 'test', topK: 5 }); console.log('SDK working:', results.results.length > 0); ``` ## Next Steps Explore all configuration options Build your first search # SDK Overview Source: https://docs.joinrefine.io/sdk/overview The complete TypeScript SDK for Refine search, recommendations, and analytics ## Introduction The `@refine-ai/sdk` package is the official TypeScript SDK for integrating Refine into your application. It provides: * **Search** — Text and image search with visual AI * **Recommendations** — Similar items, visitor, and user-based personalization * **Product Listing Pages** — Curated collections with pinned products * **Event Tracking** — Comprehensive analytics with automatic batching * **Identity Management** — Visitor, session, and user tracking * **Plugins** — Extensible architecture for consent, debugging, and auto-tracking ## Quick Example ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; // Initialize const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); // Search const results = await refine.search.text({ query: 'summer dress', topK: 24, visualWeight: 0.5 }); // Track events const context = refine.events.trackSearch('summer dress', results.results, { surface: 'search_results', totalResults: results.totalResults }); // Handle user interaction context.trackClick('sku_001', 0); // Get recommendations const recs = await refine.recs.similarItems({ anchorId: 'sku_001', topK: 8 }); // Identify logged-in users refine.identify('user_12345'); ``` ## SDK Structure The SDK is organized into namespaces: | Namespace | Purpose | | ------------------- | ---------------------------------------------- | | `refine.search` | Text and image search | | `refine.recs` | Recommendations (similar items, visitor, user) | | `refine.plp` | Product listing pages | | `refine.events` | Event tracking and queue management | | `refine.identify()` | User identification | | `refine.use()` | Plugin registration | ## Requirements * **Runtime**: Browser or Node.js 18+ * **TypeScript**: 4.7+ (optional but recommended) * **Bundle size**: \~12KB gzipped ## Documentation Install and set up the SDK All configuration options Natural language search AI-powered product recommendations Analytics and conversion tracking Error types and handling patterns # Product Listing Pages Source: https://docs.joinrefine.io/sdk/plp/overview Display curated, merchandised product collections with pinned products ## Overview Product Listing Pages (PLPs) are curated collections of products, typically used for category pages, collections, or promotional landing pages. PLPs support pinned products, intelligent ranking, and merchandising rules. ## Basic Usage ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); // Fetch a PLP by its configuration ID const plp = await refine.plp.get('plp_summer_collection'); // Get all products console.log(plp.results); // Get pinned products specifically const pinnedProducts = plp.getPinnedProducts(); ``` ## Creating PLPs PLPs are created and managed in the Refine dashboard: **Dashboard → Product Listing Pages → New PLP** Configuration options include: | Option | Description | | ------------------- | --------------------------------------------- | | **Name** | Internal name for the PLP | | **Slug** | URL-friendly identifier | | **Products** | Selected products for the collection | | **Pinned Products** | Products pinned to specific positions | | **Ranking** | Sort order (manual, popularity, newest, etc.) | | **Filters** | Default filters applied to the collection | ## Response Structure ```typescript theme={null} interface PLPResponse { results: PLPProduct[]; pinnedPositions: Map; totalResults: number; configId: string; } interface PLPProduct { productId: string; title: string; price: number; imageUrl: string; metadata: Record; isPinned: boolean; pinnedPosition?: number; } ``` ## Pinned Products Pinned products appear at specific positions regardless of the ranking algorithm: ```typescript theme={null} const plp = await refine.plp.get('plp_summer_collection'); // Get only pinned products const pinned = plp.getPinnedProducts(); // Returns products sorted by their pinned position // Check if a specific product is pinned const product = plp.results[0]; if (product.isPinned) { console.log(`Pinned at position ${product.pinnedPosition}`); } ``` ## Tracking PLP Views Track when users view and interact with PLPs: ```typescript theme={null} const plp = await refine.plp.get('plp_summer_collection'); const plpContext = refine.events.trackItemsServed({ surface: 'category_page', source: 'plp', itemIds: plp.results.map(p => p.productId), totalResults: plp.totalResults, metadata: { plpId: 'plp_summer_collection', plpName: 'Summer Collection' } }); // Track interactions plpContext.trackClick(productId, position); plpContext.trackView(productId, position); plpContext.trackAddToCart(productId); ``` ## With Filters Apply additional filters at runtime: ```typescript theme={null} const plp = await refine.plp.get('plp_summer_collection', { filters: [ { field: 'price', operator: 'lte', value: 100 }, { field: 'metadata.size', operator: 'in', value: ['S', 'M', 'L'] } ] }); ``` ## Complete Implementation ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); class CategoryPage { private plpContext: any; async load(categorySlug: string) { const plp = await refine.plp.get(categorySlug); // Track the PLP serve this.plpContext = refine.events.trackItemsServed({ surface: 'category_page', source: 'plp', itemIds: plp.results.map(p => p.productId), totalResults: plp.totalResults, metadata: { categorySlug } }); this.render(plp); return plp; } private render(plp: PLPResponse) { const container = document.getElementById('products')!; container.innerHTML = plp.results.map((product, index) => `
${product.isPinned ? 'Featured' : ''} ${product.title}

${product.title}

$${product.price.toFixed(2)}

`).join(''); this.attachEventHandlers(); } private attachEventHandlers() { document.querySelectorAll('.product').forEach(el => { const productId = (el as HTMLElement).dataset.id!; const position = parseInt((el as HTMLElement).dataset.position!); el.addEventListener('click', () => { this.plpContext?.trackClick(productId, position); }); }); } } // Usage const categoryPage = new CategoryPage(); await categoryPage.load('summer-collection'); ``` ## React Integration ```tsx theme={null} // hooks/usePLP.ts import { useState, useEffect, useRef, useCallback } from 'react'; import { refine } from '@/lib/refine'; export function usePLP(plpId: string) { const [products, setProducts] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const contextRef = useRef(null); useEffect(() => { setIsLoading(true); refine.plp.get(plpId) .then(plp => { setProducts(plp.results); contextRef.current = refine.events.trackItemsServed({ surface: 'category_page', source: 'plp', itemIds: plp.results.map(p => p.productId), totalResults: plp.totalResults, metadata: { plpId } }); }) .catch(setError) .finally(() => setIsLoading(false)); }, [plpId]); const trackClick = useCallback((productId: string, position: number) => { contextRef.current?.trackClick(productId, position); }, []); return { products, isLoading, error, trackClick }; } ``` ```tsx theme={null} // components/CategoryPage.tsx import { usePLP } from '@/hooks/usePLP'; export function CategoryPage({ slug }: { slug: string }) { const { products, isLoading, error, trackClick } = usePLP(slug); if (isLoading) return
Loading...
; if (error) return
Failed to load category
; return (
{products.map((product, index) => (
{ trackClick(product.productId, index); window.location.href = `/products/${product.productId}`; }} > {product.isPinned && Featured} {product.title}

{product.title}

${product.price.toFixed(2)}

))}
); } ``` ## Merchandising Best Practices **Pin strategically:** * Pin high-margin products at positions 1-3 * Pin new arrivals to increase visibility * Pin products with excess inventory to drive sales **Don't over-pin:** * Keep pinned products under 20% of total * Let the algorithm work for most positions * Rotate pinned products regularly ## Next Steps Track PLP interactions Apply filters to PLPs # Auto Track Plugin Source: https://docs.joinrefine.io/sdk/plugins/auto-track-plugin Automatically track page views, clicks, and viewability without manual instrumentation ## Overview The AutoTrackPlugin automatically tracks common events based on DOM elements and user interactions, reducing manual tracking code. ## Installation ```typescript theme={null} import { Refine, AutoTrackPlugin } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); refine.use(new AutoTrackPlugin({ pageViews: true, clicks: { selector: '[data-refine-item]', extractItemId: (el) => el.dataset.refineItem }, viewability: { enabled: true, threshold: 0.5, duration: 1000 } })); ``` ## Options Automatically track page view events on navigation. Configuration for automatic click tracking. Configuration for automatic viewability tracking. ## Click Tracking Automatically track clicks on product elements: ```typescript theme={null} refine.use(new AutoTrackPlugin({ clicks: { selector: '[data-refine-item]', extractItemId: (el) => el.dataset.refineItem, extractPosition: (el) => parseInt(el.dataset.position || '0') } })); ``` ### Click Config Options CSS selector for clickable product elements. Function to extract the product ID from a clicked element. Function to extract the position from a clicked element. Defaults to 0. ### HTML Setup for Click Tracking ```html theme={null}
Product 1

Product Title

Product 2

Product Title

``` ## Viewability Tracking Automatically track when products become visible: ```typescript theme={null} refine.use(new AutoTrackPlugin({ viewability: { enabled: true, selector: '[data-refine-item]', threshold: 0.5, // 50% visible duration: 1000, // for 1 second extractItemId: (el) => el.dataset.refineItem, extractPosition: (el) => parseInt(el.dataset.position || '0') } })); ``` ### Viewability Config Options Enable automatic viewability tracking. CSS selector for viewable elements. Defaults to clicks.selector. Percentage of element that must be visible (0.0 to 1.0). Milliseconds element must be visible before tracking. Function to extract product ID. Defaults to clicks.extractItemId. Function to extract position. Defaults to clicks.extractPosition. ## Page View Tracking Track page views automatically: ```typescript theme={null} refine.use(new AutoTrackPlugin({ pageViews: true })); ``` This tracks: * Initial page load * SPA navigation (using History API) * Hash changes ## Complete Configuration ```typescript theme={null} import { Refine, AutoTrackPlugin } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); refine.use(new AutoTrackPlugin({ // Track page views pageViews: true, // Track clicks on product cards clicks: { selector: '[data-refine-item]', extractItemId: (el) => { return (el as HTMLElement).dataset.refineItem || ''; }, extractPosition: (el) => { return parseInt((el as HTMLElement).dataset.position || '0'); } }, // Track viewability viewability: { enabled: true, threshold: 0.5, duration: 1000 } })); ``` ## HTML Data Attributes The plugin expects specific data attributes on your product elements: ```html theme={null}
``` ### Required Attributes | Attribute | Purpose | | ------------------ | ----------------------------------- | | `data-refine-item` | Product ID for the element | | `data-position` | Position in the results (0-indexed) | ### Optional Attributes | Attribute | Purpose | | ---------------------- | ----------------------------- | | `data-refine-surface` | Where products are displayed | | `data-refine-source` | How products were generated | | `data-refine-serve-id` | Links to original serve event | ## Dynamic Content For dynamically loaded content, the plugin uses MutationObserver to detect new elements: ```typescript theme={null} // New products added dynamically are automatically tracked const newProduct = document.createElement('div'); newProduct.className = 'product'; newProduct.dataset.refineItem = 'sku_new'; newProduct.dataset.position = '24'; document.getElementById('search-results').appendChild(newProduct); // Plugin automatically starts tracking this element ``` ## Combining with Manual Tracking You can use AutoTrackPlugin alongside manual tracking: ```typescript theme={null} // Auto-track plugin handles clicks and views refine.use(new AutoTrackPlugin({ clicks: { selector: '[data-refine-item]', extractItemId: (el) => el.dataset.refineItem }, viewability: { enabled: true, threshold: 0.5, duration: 1000 } })); // Manual tracking for search (to get the context) const results = await refine.search.text({ query: 'shoes', topK: 24 }); const searchContext = refine.events.trackSearch('shoes', results.results, { surface: 'search_results', totalResults: results.totalResults }); // Render products with data attributes renderProducts(results.results); // Auto-track plugin will handle click and view tracking ``` ## Framework Integration ### React ```tsx theme={null} import { useEffect } from 'react'; import { refine } from '@/lib/refine'; import { AutoTrackPlugin } from '@refine-ai/sdk'; export function ProductGrid({ products }) { useEffect(() => { // Plugin is typically initialized once at app level // But you can re-configure for specific pages }, []); return (
{products.map((product, index) => (
{product.title}

{product.title}

${product.price}

))}
); } ``` ### Vue ```vue theme={null} ``` ## Debugging Auto-Track Combine with DebugPlugin to see what's being tracked: ```typescript theme={null} refine.use(new DebugPlugin({ logEvents: true })); refine.use(new AutoTrackPlugin({ pageViews: true, clicks: { selector: '[data-refine-item]', extractItemId: el => el.dataset.refineItem }, viewability: { enabled: true, threshold: 0.5, duration: 1000 } })); // Console will show: // [Refine AutoTrack] Click detected: sku_001 at position 3 // [Refine AutoTrack] View tracked: sku_002 at position 0 // [Refine AutoTrack] Page view: /products/shoes ``` ## Next Steps Development tools Privacy compliance # Consent Plugin Source: https://docs.joinrefine.io/sdk/plugins/consent-plugin GDPR-compliant consent management for event tracking ## Overview The ConsentPlugin gates event tracking behind user consent, helping you comply with GDPR, CCPA, and other privacy regulations. ## Installation ```typescript theme={null} import { Refine, ConsentPlugin } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', privacy: { requireConsent: true } }); const consentPlugin = new ConsentPlugin({ required: true, onConsentRequired: () => { showConsentBanner(); } }); refine.use(consentPlugin); ``` ## Options When true, all event tracking is paused until consent is granted. Callback fired when an event is attempted but consent hasn't been granted. Use this to show your consent UI. ## Methods ### grant() Grant consent and start tracking: ```typescript theme={null} consentPlugin.grant(); ``` When called: * Event tracking resumes immediately * Queued events are sent * Consent state is persisted in localStorage ### deny() Deny consent and disable tracking: ```typescript theme={null} consentPlugin.deny(); ``` When called: * Event tracking is disabled * Queued events are discarded * Consent state is persisted ### getStatus() Check current consent status: ```typescript theme={null} const status = consentPlugin.getStatus(); console.log(status); // 'granted' | 'denied' | 'pending' ``` ### reset() Clear consent state (user can be asked again): ```typescript theme={null} consentPlugin.reset(); ``` ## Complete Implementation ```typescript theme={null} import { Refine, ConsentPlugin } from '@refine-ai/sdk'; // Initialize SDK const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', privacy: { requireConsent: true, anonymizeIp: true } }); // Initialize consent plugin const consentPlugin = new ConsentPlugin({ required: true, onConsentRequired: () => { // Show banner only if not already decided if (consentPlugin.getStatus() === 'pending') { document.getElementById('consent-banner')?.classList.remove('hidden'); } } }); refine.use(consentPlugin); // UI Event Handlers document.getElementById('accept-all')?.addEventListener('click', () => { consentPlugin.grant(); hideConsentBanner(); }); document.getElementById('reject-all')?.addEventListener('click', () => { consentPlugin.deny(); hideConsentBanner(); }); document.getElementById('manage-preferences')?.addEventListener('click', () => { showPreferencesModal(); }); function hideConsentBanner() { document.getElementById('consent-banner')?.classList.add('hidden'); } function showPreferencesModal() { // Your preferences UI } ``` ## Consent Banner HTML ```html theme={null} ``` ## Behavior Before Consent When consent is required but not yet granted: | Action | Behavior | | ---------------------- | ------------------------------------------- | | Search/Recommendations | Works normally (required for functionality) | | Event tracking | Events are queued but not sent | | Identity | Visitor ID generated but not persisted | After consent is granted, queued events are sent and identity is persisted. ## Integration with Cookie Consent Tools ### OneTrust Integration ```typescript theme={null} // Listen for OneTrust consent changes window.OptanonWrapper = function() { const activeGroups = window.OnetrustActiveGroups || ''; if (activeGroups.includes('C0002')) { // Performance cookies accepted consentPlugin.grant(); } else { consentPlugin.deny(); } }; ``` ### Cookiebot Integration ```typescript theme={null} window.addEventListener('CookiebotOnAccept', () => { if (Cookiebot.consent.statistics) { consentPlugin.grant(); } }); window.addEventListener('CookiebotOnDecline', () => { consentPlugin.deny(); }); ``` ### Custom CMP Integration ```typescript theme={null} // Generic CMP integration pattern function handleConsentChange(consent: { analytics: boolean }) { if (consent.analytics) { consentPlugin.grant(); } else { consentPlugin.deny(); } } // Register with your CMP yourCMP.onConsentChange(handleConsentChange); ``` ## Persistence Consent state is stored in localStorage under `refine_consent`: ```javascript theme={null} // Stored value localStorage.getItem('refine_consent') // Returns: "granted" | "denied" | null ``` The consent persists across sessions until: * User clears browser data * You call `consentPlugin.reset()` * User explicitly changes their preference ## Testing Consent Flow ```typescript theme={null} import { Refine, ConsentPlugin, DebugPlugin } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); // Debug plugin to see what's happening refine.use(new DebugPlugin({ logEvents: true })); const consentPlugin = new ConsentPlugin({ required: true, onConsentRequired: () => { console.log('Consent required - showing banner'); } }); refine.use(consentPlugin); // Test the flow console.log('Status:', consentPlugin.getStatus()); // 'pending' // Try to track something refine.events.trackSearch('test', [], { surface: 'test', totalResults: 0 }); // Console: "Consent required - showing banner" // Event is queued but not sent // Grant consent consentPlugin.grant(); console.log('Status:', consentPlugin.getStatus()); // 'granted' // Queued events are now sent // Test denial consentPlugin.reset(); consentPlugin.deny(); console.log('Status:', consentPlugin.getStatus()); // 'denied' // No events will be tracked ``` ## Privacy Configuration Combine with SDK privacy settings: ```typescript theme={null} const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', privacy: { respectDoNotTrack: true, // Honor browser DNT anonymizeIp: true, // Anonymize IPs requireConsent: true // Wait for consent } }); ``` ## Next Steps Development tools Automatic tracking # Debug Plugin Source: https://docs.joinrefine.io/sdk/plugins/debug-plugin Development logging, event validation, and dry-run mode ## Overview The DebugPlugin helps during development by logging events, validating parameters, and optionally preventing events from being sent. ## Installation ```typescript theme={null} import { Refine, DebugPlugin } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); refine.use(new DebugPlugin({ logEvents: true, validateEvents: true, dryRun: false })); ``` ## Options Log all events to the browser console with formatted output. Validate event parameters and warn about potential issues. Prevent events from being sent to the server. Useful for testing. ## Console Output With `logEvents: true`, you'll see detailed logs: ``` [Refine] trackSearch query: "summer dress" surface: "search_results" itemCount: 24 totalResults: 847 [Refine] trackClick itemId: "sku_001" position: 3 serveId: "srv_abc123" [Refine] trackPurchase orderId: "order_789" value: 149.99 currency: "USD" items: 2 ``` ## Validation Warnings With `validateEvents: true`, the plugin warns about common issues: ``` [Refine Warning] trackClick called with position > 100. This may indicate incorrect position tracking. Position: 247 [Refine Warning] trackPurchase item "sku_unknown" not found in recent serves. This item may not be attributable to a search/recommendation. [Refine Warning] trackView called before trackItemsServed. Ensure items are served before tracking views. ``` ## Dry Run Mode With `dryRun: true`, events are processed but not sent: ```typescript theme={null} refine.use(new DebugPlugin({ logEvents: true, dryRun: true // Events won't reach the server })); // This will be logged but not sent refine.events.trackPurchase({ orderId: 'test_order', value: 99.99, currency: 'USD', items: [{ itemId: 'test_sku', quantity: 1, unitPrice: 99.99 }] }); // Console shows: // [Refine] trackPurchase (DRY RUN - not sent) // orderId: "test_order" // ... ``` ## Development vs Production Only enable in development: ```typescript theme={null} import { Refine, DebugPlugin } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); if (process.env.NODE_ENV === 'development') { refine.use(new DebugPlugin({ logEvents: true, validateEvents: true, dryRun: false })); } ``` ## Debugging Specific Issues ### Missing Event Attribution ```typescript theme={null} // Enable verbose logging refine.use(new DebugPlugin({ logEvents: true, validateEvents: true })); // Search const results = await refine.search.text({ query: 'shoes', topK: 20 }); const context = refine.events.trackSearch('shoes', results.results, { surface: 'search_results', totalResults: results.totalResults }); // Click - if position is wrong, you'll see a warning context.trackClick('sku_001', 3); // [Refine] trackClick // itemId: "sku_001" // position: 3 // serveId: "srv_abc123" ``` ### Event Queue Issues ```typescript theme={null} // Check queue status const metrics = refine.events.getMetrics(); console.log(metrics); // { queued: 5, sent: 142, failed: 2, retrying: 1 } // Force flush to debug sending issues await refine.events.flush(); ``` ### Identity Verification ```typescript theme={null} // Log current identity state console.log('Visitor:', refine.getVisitorId()); console.log('Session:', refine.getSessionId()); console.log('User:', refine.getUserId()); ``` ## Testing Integration Use dry run mode for automated tests: ```typescript theme={null} // test/search.test.ts import { Refine, DebugPlugin } from '@refine-ai/sdk'; describe('Search tracking', () => { let refine: Refine; let debugPlugin: DebugPlugin; beforeEach(() => { refine = new Refine({ apiKey: 'test-key', organizationId: 'test-org', catalogId: 'test-catalog' }); debugPlugin = new DebugPlugin({ logEvents: false, // Quiet in tests validateEvents: true, dryRun: true // Don't send real events }); refine.use(debugPlugin); }); it('should track search events', async () => { const context = refine.events.trackSearch( 'test query', [{ productId: 'sku_001' }], { surface: 'search_results', totalResults: 1 } ); // Event is validated but not sent expect(context).toBeDefined(); }); }); ``` ## Next Steps Privacy compliance Automatic tracking # Plugins Overview Source: https://docs.joinrefine.io/sdk/plugins/overview Extend SDK functionality with built-in and custom plugins ## Overview Plugins extend the Refine SDK with additional functionality. The SDK includes three built-in plugins: | Plugin | Purpose | | ------------------------------------------------- | ---------------------------------- | | [DebugPlugin](/sdk/plugins/debug-plugin) | Development logging and validation | | [ConsentPlugin](/sdk/plugins/consent-plugin) | GDPR-compliant consent management | | [AutoTrackPlugin](/sdk/plugins/auto-track-plugin) | Automatic event tracking | ## Using Plugins Register plugins with `refine.use()`: ```typescript theme={null} import { Refine, DebugPlugin, ConsentPlugin, AutoTrackPlugin } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); // Add plugins refine.use(new DebugPlugin({ logEvents: true })); refine.use(new ConsentPlugin({ required: true })); refine.use(new AutoTrackPlugin({ pageViews: true })); ``` ## Plugin Order Plugins execute in registration order. For most cases, the recommended order is: ```typescript theme={null} // 1. Debug first (logs everything) refine.use(new DebugPlugin({ logEvents: true })); // 2. Consent second (gates all tracking) refine.use(new ConsentPlugin({ required: true })); // 3. AutoTrack last (depends on consent) refine.use(new AutoTrackPlugin({ pageViews: true })); ``` ## Quick Reference ### DebugPlugin Log events and validate parameters during development: ```typescript theme={null} import { DebugPlugin } from '@refine-ai/sdk'; refine.use(new DebugPlugin({ logEvents: true, // Log all events to console validateEvents: true, // Warn about invalid events dryRun: false // If true, don't send events })); ``` ### ConsentPlugin Gate tracking behind user consent: ```typescript theme={null} import { ConsentPlugin } from '@refine-ai/sdk'; const consentPlugin = new ConsentPlugin({ required: true, onConsentRequired: () => { showConsentBanner(); } }); refine.use(consentPlugin); // When user grants consent consentPlugin.grant(); // When user denies consent consentPlugin.deny(); ``` ### AutoTrackPlugin Automatically track common events: ```typescript theme={null} import { AutoTrackPlugin } from '@refine-ai/sdk'; refine.use(new AutoTrackPlugin({ pageViews: true, clicks: { selector: '[data-refine-item]', extractItemId: (el) => el.dataset.refineItem }, viewability: { enabled: true, threshold: 0.5, duration: 1000 } })); ``` ## Combining Plugins Typical production setup: ```typescript theme={null} import { Refine, DebugPlugin, ConsentPlugin, AutoTrackPlugin } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', privacy: { requireConsent: true } }); // Development: enable debug logging if (process.env.NODE_ENV === 'development') { refine.use(new DebugPlugin({ logEvents: true, validateEvents: true })); } // Production: consent management const consentPlugin = new ConsentPlugin({ required: true, onConsentRequired: () => { document.getElementById('consent-banner')?.classList.remove('hidden'); } }); refine.use(consentPlugin); // Auto-tracking with consent gate refine.use(new AutoTrackPlugin({ pageViews: true, viewability: { enabled: true, threshold: 0.5, duration: 1000 } })); // Consent UI handlers document.getElementById('accept-cookies')?.addEventListener('click', () => { consentPlugin.grant(); document.getElementById('consent-banner')?.classList.add('hidden'); }); document.getElementById('decline-cookies')?.addEventListener('click', () => { consentPlugin.deny(); document.getElementById('consent-banner')?.classList.add('hidden'); }); ``` ## Next Steps Development tools Privacy compliance Automatic tracking # React Integration Source: https://docs.joinrefine.io/sdk/react-integration Patterns and hooks for using Refine in React applications ## Overview This guide covers patterns for integrating Refine into React applications, including custom hooks, context providers, and component patterns. ## Setup ### Create SDK Instance ```typescript theme={null} // lib/refine.ts import { Refine } from '@refine-ai/sdk'; export const refine = new Refine({ apiKey: process.env.NEXT_PUBLIC_REFINE_API_KEY!, organizationId: process.env.NEXT_PUBLIC_REFINE_ORG_ID!, catalogId: process.env.NEXT_PUBLIC_REFINE_CATALOG_ID! }); ``` ### Context Provider ```tsx theme={null} // contexts/RefineContext.tsx import { createContext, useContext, ReactNode } from 'react'; import { Refine } from '@refine-ai/sdk'; import { refine } from '@/lib/refine'; const RefineContext = createContext(null); export function RefineProvider({ children }: { children: ReactNode }) { return ( {children} ); } export function useRefine(): Refine { const context = useContext(RefineContext); if (!context) { throw new Error('useRefine must be used within RefineProvider'); } return context; } ``` ## Custom Hooks ### useSearch ```tsx theme={null} // hooks/useSearch.ts import { useState, useCallback, useRef } from 'react'; import { refine } from '@/lib/refine'; import type { SearchResponse, Filter, SortBy } from '@refine-ai/sdk'; interface UseSearchOptions { topK?: number; visualWeight?: number; filters?: Filter[]; sortBy?: SortBy; } interface UseSearchResult { results: SearchResponse['results']; totalResults: number; isLoading: boolean; error: Error | null; search: (query: string) => Promise; trackClick: (productId: string, position: number) => void; trackView: (productId: string, position: number) => void; trackAddToCart: (productId: string) => void; } export function useSearch(options: UseSearchOptions = {}): UseSearchResult { const [results, setResults] = useState([]); const [totalResults, setTotalResults] = useState(0); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const contextRef = useRef(null); const search = useCallback(async (query: string) => { if (!query.trim()) { setResults([]); setTotalResults(0); return; } setIsLoading(true); setError(null); try { const response = await refine.search.text({ query, topK: options.topK || 24, visualWeight: options.visualWeight, filters: options.filters, sortBy: options.sortBy }); setResults(response.results); setTotalResults(response.totalResults); // Create tracking context contextRef.current = refine.events.trackSearch(query, response.results, { surface: 'search_results', totalResults: response.totalResults }); } catch (err) { setError(err as Error); setResults([]); setTotalResults(0); } finally { setIsLoading(false); } }, [options.topK, options.visualWeight, options.filters, options.sortBy]); const trackClick = useCallback((productId: string, position: number) => { contextRef.current?.trackClick(productId, position); }, []); const trackView = useCallback((productId: string, position: number) => { contextRef.current?.trackView(productId, position); }, []); const trackAddToCart = useCallback((productId: string) => { contextRef.current?.trackAddToCart(productId); }, []); return { results, totalResults, isLoading, error, search, trackClick, trackView, trackAddToCart }; } ``` ### useRecommendations ```tsx theme={null} // hooks/useRecommendations.ts import { useState, useCallback, useEffect, useRef } from 'react'; import { refine } from '@/lib/refine'; import type { RecommendationResponse } from '@refine-ai/sdk'; interface UseRecommendationsResult { recommendations: RecommendationResponse['results']; isLoading: boolean; error: Error | null; trackClick: (productId: string, position: number) => void; trackAddToCart: (productId: string) => void; } export function useSimilarItems( anchorId: string, topK: number = 8 ): UseRecommendationsResult { const [recommendations, setRecommendations] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const contextRef = useRef(null); useEffect(() => { if (!anchorId) return; setIsLoading(true); setError(null); refine.recs.similarItems({ anchorId, topK }) .then(response => { setRecommendations(response.results); contextRef.current = refine.events.trackRecommendations( response.serveId, response.results, 'product_page', 'similar-items', { anchorId } ); }) .catch(err => { setError(err); setRecommendations([]); }) .finally(() => setIsLoading(false)); }, [anchorId, topK]); const trackClick = useCallback((productId: string, position: number) => { contextRef.current?.trackClick(productId, position); }, []); const trackAddToCart = useCallback((productId: string) => { contextRef.current?.trackAddToCart(productId); }, []); return { recommendations, isLoading, error, trackClick, trackAddToCart }; } export function useVisitorRecommendations( configId: string, topK: number = 12 ): UseRecommendationsResult { const [recommendations, setRecommendations] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const contextRef = useRef(null); useEffect(() => { refine.recs.forVisitor({ configId, topK }) .then(response => { setRecommendations(response.results); contextRef.current = refine.events.trackRecommendations( response.serveId, response.results, 'home_page', 'visitor-recs' ); }) .catch(err => { setError(err); setRecommendations([]); }) .finally(() => setIsLoading(false)); }, [configId, topK]); const trackClick = useCallback((productId: string, position: number) => { contextRef.current?.trackClick(productId, position); }, []); const trackAddToCart = useCallback((productId: string) => { contextRef.current?.trackAddToCart(productId); }, []); return { recommendations, isLoading, error, trackClick, trackAddToCart }; } ``` ### useViewability ```tsx theme={null} // hooks/useViewability.ts import { useEffect, useRef } from 'react'; export function useViewability( onView: (productId: string, position: number) => void, threshold: number = 0.5, duration: number = 1000 ) { const observerRef = useRef(null); const viewedRef = useRef>(new Set()); const timersRef = useRef>(new Map()); useEffect(() => { observerRef.current = new IntersectionObserver( (entries) => { entries.forEach(entry => { const el = entry.target as HTMLElement; const productId = el.dataset.productId; const position = parseInt(el.dataset.position || '0'); if (!productId || viewedRef.current.has(productId)) return; if (entry.isIntersecting) { const timer = setTimeout(() => { if (viewedRef.current.has(productId)) return; viewedRef.current.add(productId); onView(productId, position); }, duration); timersRef.current.set(productId, timer); } else { const timer = timersRef.current.get(productId); if (timer) { clearTimeout(timer); timersRef.current.delete(productId); } } }); }, { threshold } ); return () => { observerRef.current?.disconnect(); timersRef.current.forEach(clearTimeout); }; }, [onView, threshold, duration]); const observe = useCallback((element: HTMLElement | null) => { if (element) { observerRef.current?.observe(element); } }, []); return { observe }; } ``` ## Component Patterns ### Search Results Page ```tsx theme={null} // components/SearchPage.tsx import { useState, FormEvent } from 'react'; import { useSearch } from '@/hooks/useSearch'; import { ProductCard } from './ProductCard'; export function SearchPage() { const [query, setQuery] = useState(''); const { results, totalResults, isLoading, error, search, trackClick, trackView, trackAddToCart } = useSearch({ topK: 24 }); const handleSubmit = (e: FormEvent) => { e.preventDefault(); search(query); }; return (
setQuery(e.target.value)} placeholder="Search products..." />
{isLoading &&
Searching...
} {error &&
Search failed. Please try again.
} {results.length > 0 && ( <>

Showing {results.length} of {totalResults} results

{results.map((product, index) => ( trackView(product.productId, index)} onClick={() => trackClick(product.productId, index)} onAddToCart={() => trackAddToCart(product.productId)} /> ))}
)}
); } ``` ### Product Card with Viewability ```tsx theme={null} // components/ProductCard.tsx import { useRef, useEffect } from 'react'; interface ProductCardProps { product: { productId: string; title: string; price: number; imageUrl: string; }; position: number; onView: () => void; onClick: () => void; onAddToCart: () => void; } export function ProductCard({ product, position, onView, onClick, onAddToCart }: ProductCardProps) { const cardRef = useRef(null); const hasViewed = useRef(false); useEffect(() => { const card = cardRef.current; if (!card) return; const observer = new IntersectionObserver( ([entry]) => { if (entry.isIntersecting && !hasViewed.current) { const timer = setTimeout(() => { if (!hasViewed.current) { hasViewed.current = true; onView(); } }, 1000); return () => clearTimeout(timer); } }, { threshold: 0.5 } ); observer.observe(card); return () => observer.disconnect(); }, [onView]); const handleClick = () => { onClick(); window.location.href = `/products/${product.productId}`; }; const handleAddToCart = (e: React.MouseEvent) => { e.stopPropagation(); onAddToCart(); // Add to cart logic }; return (
{product.title}

{product.title}

${product.price.toFixed(2)}

); } ``` ### Similar Items Carousel ```tsx theme={null} // components/SimilarItems.tsx import { useSimilarItems } from '@/hooks/useRecommendations'; import { ProductCard } from './ProductCard'; interface SimilarItemsProps { productId: string; } export function SimilarItems({ productId }: SimilarItemsProps) { const { recommendations, isLoading, error, trackClick, trackAddToCart } = useSimilarItems(productId, 8); if (isLoading) { return
Loading recommendations...
; } if (error || recommendations.length === 0) { return null; } return (

You May Also Like

{recommendations.map((product, index) => ( {}} onClick={() => trackClick(product.productId, index)} onAddToCart={() => trackAddToCart(product.productId)} /> ))}
); } ``` ## Identity Management ### Auth Integration ```tsx theme={null} // hooks/useRefineAuth.ts import { useEffect } from 'react'; import { refine } from '@/lib/refine'; import { useAuth } from '@/contexts/AuthContext'; export function useRefineAuth() { const { user, isAuthenticated } = useAuth(); useEffect(() => { if (isAuthenticated && user?.id) { refine.identify(user.id); } }, [isAuthenticated, user?.id]); const logout = () => { refine.reset(); }; return { logout }; } ``` ### Provider with Auth ```tsx theme={null} // app/layout.tsx 'use client'; import { RefineProvider } from '@/contexts/RefineContext'; import { AuthProvider } from '@/contexts/AuthContext'; import { useRefineAuth } from '@/hooks/useRefineAuth'; function RefineAuthSync({ children }) { useRefineAuth(); return children; } export default function RootLayout({ children }) { return ( {children} ); } ``` ## Purchase Tracking ```tsx theme={null} // hooks/usePurchaseTracking.ts import { useCallback } from 'react'; import { refine } from '@/lib/refine'; interface OrderItem { productId: string; quantity: number; price: number; } interface Order { id: string; total: number; currency: string; items: OrderItem[]; } export function usePurchaseTracking() { const trackPurchase = useCallback(async (order: Order) => { refine.events.trackPurchase({ orderId: order.id, value: order.total, currency: order.currency, items: order.items.map(item => ({ itemId: item.productId, quantity: item.quantity, unitPrice: item.price })) }); await refine.events.flush(); }, []); return { trackPurchase }; } ``` ## Next Steps SSR and API patterns Complete event tracking guide # Recommendations Overview Source: https://docs.joinrefine.io/sdk/recommendations/overview AI-powered product recommendations with visual similarity and behavioral signals ## Overview Refine provides three types of recommendations, each optimized for different use cases: | Type | Best For | Data Required | | ----------------------------------------------------------------------- | ---------------------------------- | ---------------------------- | | [Similar Items](/sdk/recommendations/similar-items) | Product pages, "You may also like" | Anchor product ID | | [Visitor Recommendations](/sdk/recommendations/visitor-recommendations) | Homepage, anonymous users | Browsing history (automatic) | | [User Recommendations](/sdk/recommendations/user-recommendations) | Logged-in users, personalization | User identification | ## Quick Start ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); // Similar items (product page) const similar = await refine.recs.similarItems({ anchorId: 'sku_dress_001', topK: 8 }); // Visitor recommendations (homepage, anonymous) const forVisitor = await refine.recs.forVisitor({ configId: 'homepage_recs', topK: 12 }); // User recommendations (logged-in users) refine.identify('user_12345'); const forUser = await refine.recs.forUser({ configId: 'personalized_picks', topK: 12 }); ``` ## Configuration IDs Visitor and user recommendations require a `configId` that references a recommendation configuration created in the Refine dashboard. Configurations define: * **Strategy** — Collaborative filtering, content-based, hybrid * **Weighting** — Balance between visual similarity and behavioral signals * **Filters** — Default filters applied to all recommendations * **Business rules** — Category diversity, price range constraints Create configurations at: **Dashboard → Recommendations → Configurations** Similar items don't require a configId — they work directly with any product in your catalog. ## Tracking Recommendations Always track when recommendations are served to enable analytics and feedback loops: ```typescript theme={null} const recs = await refine.recs.similarItems({ anchorId: 'sku_001', topK: 8 }); const recsContext = refine.events.trackRecommendations( recs.serveId, recs.results, 'product_page', // surface 'similar-items', // source { anchorId: 'sku_001' } ); // Track user interactions recsContext.trackClick(productId, position); recsContext.trackView(productId, position); recsContext.trackAddToCart(productId); ``` ## Response Structure All recommendation methods return the same structure: ```typescript theme={null} interface RecommendationResponse { results: RecommendationItem[]; serveId: string; totalResults: number; } interface RecommendationItem { productId: string; title: string; price: number; imageUrl: string; metadata: Record; score: number; } ``` Array of recommended products, ordered by relevance/score. Unique identifier for this recommendation serve. Used for event tracking. Total number of available recommendations before `topK` limit. ## Filtering Recommendations Apply filters to narrow recommendations: ```typescript theme={null} const recs = await refine.recs.similarItems({ anchorId: 'sku_dress_001', topK: 8, filters: [ { field: 'price', operator: 'lte', value: 150 }, { field: 'stock', operator: 'gt', value: 0 }, { field: 'metadata.category', operator: 'eq', value: 'dresses' } ] }); ``` See [Filters](/sdk/search/filters) for all available operators. ## Visual Weight For similar items, control the balance between visual similarity and other signals: ```typescript theme={null} const recs = await refine.recs.similarItems({ anchorId: 'sku_001', topK: 8, visualWeight: 0.7 // High visual similarity emphasis }); ``` | visualWeight | Behavior | | ------------ | --------------------------------- | | `0.0` | Pure metadata/behavioral matching | | `0.5` | Balanced (default for most) | | `1.0` | Pure visual similarity | ## Recommendation Strategies by Page | Page | Recommended Type | Configuration | | -------------------- | ---------------- | ---------------------------- | | Product Detail Page | Similar Items | `anchorId` = current product | | Homepage (anonymous) | Visitor Recs | Popular/trending config | | Homepage (logged-in) | User Recs | Personalized config | | Cart Page | Similar Items | Multiple anchors from cart | | Category Page | Visitor Recs | Category-specific config | | Search (no results) | Visitor Recs | Fallback/popular config | ## Error Handling ```typescript theme={null} import { RefineNotFoundError, RefineValidationError } from '@refine-ai/sdk'; try { const recs = await refine.recs.similarItems({ anchorId: 'invalid_sku', topK: 8 }); } catch (error) { if (error instanceof RefineNotFoundError) { // Anchor product doesn't exist console.log('Product not found, showing popular items instead'); return await refine.recs.forVisitor({ configId: 'popular', topK: 8 }); } if (error instanceof RefineValidationError) { console.error('Invalid parameters:', error.message); } } ``` ## Next Steps Product-based recommendations Anonymous visitor personalization Logged-in user personalization Track recommendation interactions # Similar Items Source: https://docs.joinrefine.io/sdk/recommendations/similar-items Find products visually and contextually similar to a specific product ## Overview Similar items recommendations find products that look like and relate to a specific anchor product. Use them on product detail pages for "You may also like" carousels. ## Basic Usage ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); const recs = await refine.recs.similarItems({ anchorId: 'sku_dress_001', topK: 8 }); recs.results.forEach(product => { console.log(`${product.title} - $${product.price}`); }); ``` ## Parameters The product ID to find similar items for. This is typically the currently viewed product. Number of recommendations to return. Recommended: 4-12 for carousels. Optional configuration ID from the dashboard. Applies preset filters and business rules. Balance between visual similarity and other signals (0.0 to 1.0). Include full product metadata in results. Additional filters to apply. See [Filters](/sdk/search/filters). ## With Filters Ensure recommended products are available and appropriately priced: ```typescript theme={null} const recs = await refine.recs.similarItems({ anchorId: 'sku_dress_001', topK: 8, visualWeight: 0.7, filters: [ { field: 'stock', operator: 'gt', value: 0 }, { field: 'price', operator: 'gte', value: 30 }, { field: 'price', operator: 'lte', value: 150 }, { field: 'productId', operator: 'ne', value: 'sku_dress_001' } // Exclude anchor ] }); ``` The anchor product is automatically excluded from results. The explicit `ne` filter above is optional and shown for clarity. ## Visual Weight Tuning Adjust `visualWeight` based on product category: ```typescript theme={null} // Fashion: High visual weight (appearance matters) const fashionRecs = await refine.recs.similarItems({ anchorId: 'sku_dress_001', topK: 8, visualWeight: 0.8 }); // Electronics: Lower visual weight (specs matter more) const techRecs = await refine.recs.similarItems({ anchorId: 'sku_laptop_001', topK: 8, visualWeight: 0.3 }); // Furniture: Balanced const furnitureRecs = await refine.recs.similarItems({ anchorId: 'sku_chair_001', topK: 8, visualWeight: 0.5 }); ``` ## Tracking Similar Items Track impressions and interactions: ```typescript theme={null} const recs = await refine.recs.similarItems({ anchorId: 'sku_001', topK: 8 }); const recsContext = refine.events.trackRecommendations( recs.serveId, recs.results, 'product_page', 'similar-items', { anchorId: 'sku_001' } ); // User clicks a recommendation function handleProductClick(productId: string, position: number) { recsContext.trackClick(productId, position); navigateToProduct(productId); } // User adds recommended item to cart function handleAddToCart(productId: string) { recsContext.trackAddToCart(productId); addToCart(productId); } ``` ## Complete Implementation ```typescript theme={null} import { Refine, RefineNotFoundError } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); interface SimilarItemsCarouselProps { productId: string; maxItems?: number; } async function loadSimilarItems({ productId, maxItems = 8 }: SimilarItemsCarouselProps) { try { const recs = await refine.recs.similarItems({ anchorId: productId, topK: maxItems, visualWeight: 0.7, filters: [ { field: 'stock', operator: 'gt', value: 0 } ] }); // Track recommendations const context = refine.events.trackRecommendations( recs.serveId, recs.results, 'product_page', 'similar-items', { anchorId: productId } ); return { products: recs.results, trackClick: (id: string, pos: number) => context.trackClick(id, pos), trackAddToCart: (id: string) => context.trackAddToCart(id) }; } catch (error) { if (error instanceof RefineNotFoundError) { // Product not in catalog, return empty console.warn(`Product ${productId} not found for similar items`); return { products: [], trackClick: () => {}, trackAddToCart: () => {} }; } throw error; } } // Usage const { products, trackClick, trackAddToCart } = await loadSimilarItems({ productId: 'sku_dress_001' }); // Render carousel products.forEach((product, index) => { const element = createProductCard(product); element.onclick = () => { trackClick(product.productId, index); window.location.href = `/products/${product.productId}`; }; element.querySelector('.add-to-cart').onclick = (e) => { e.stopPropagation(); trackAddToCart(product.productId); }; }); ``` ## Cross-Sell from Cart Get similar items for multiple products in the cart: ```typescript theme={null} async function getCartCrossSells(cartItems: string[]) { // Get similar items for the first few cart items const anchors = cartItems.slice(0, 3); const allRecs = await Promise.all( anchors.map(anchorId => refine.recs.similarItems({ anchorId, topK: 4, filters: [ { field: 'productId', operator: 'nin', value: cartItems }, { field: 'stock', operator: 'gt', value: 0 } ] }) ) ); // Deduplicate and combine const seen = new Set(); const combined = allRecs.flatMap(r => r.results).filter(product => { if (seen.has(product.productId)) return false; seen.add(product.productId); return true; }); return combined.slice(0, 8); } ``` ## Error Handling ```typescript theme={null} import { RefineNotFoundError, RefineValidationError } from '@refine-ai/sdk'; async function getSimilarItems(productId: string) { try { return await refine.recs.similarItems({ anchorId: productId, topK: 8 }); } catch (error) { if (error instanceof RefineNotFoundError) { // Anchor product doesn't exist in catalog // Fall back to popular items return await refine.recs.forVisitor({ configId: 'popular_items', topK: 8 }); } if (error instanceof RefineValidationError) { console.error('Invalid request:', error.message); return { results: [] }; } throw error; } } ``` ## Next Steps Anonymous visitor personalization Logged-in user personalization # User Recommendations Source: https://docs.joinrefine.io/sdk/recommendations/user-recommendations Personalized recommendations for logged-in users with cross-device history ## Overview User recommendations provide the deepest level of personalization by leveraging a user's full purchase and browsing history across sessions and devices. Requires calling `refine.identify()` with your user ID. ## Basic Usage ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); // Identify the logged-in user refine.identify('user_12345'); // Get personalized recommendations const recs = await refine.recs.forUser({ configId: 'personalized_picks', topK: 12 }); recs.results.forEach(product => { console.log(`${product.title} - $${product.price}`); }); ``` ## Parameters Recommendation configuration ID from the dashboard. Number of recommendations to return. Additional filters to apply. See [Filters](/sdk/search/filters). ## User Identification Before requesting user recommendations, you must identify the user: ```typescript theme={null} // Call this when user logs in refine.identify('user_12345'); // Now user recommendations will work const recs = await refine.recs.forUser({ configId: 'picks', topK: 12 }); ``` If you call `forUser()` without first calling `identify()`, the request will fail with a validation error. ### Identity Flow ```typescript theme={null} // 1. User arrives (anonymous) const visitorId = refine.getVisitorId(); // Auto-generated // 2. User browses products await refine.search.text({ query: 'shoes', topK: 20 }); // Browsing tracked under visitorId // 3. User logs in refine.identify('user_12345'); // Previous visitor behavior now linked to user // 4. Get personalized recommendations const recs = await refine.recs.forUser({ configId: 'personalized_picks', topK: 12 }); // Uses full user history including current session ``` ### Check Current Identity ```typescript theme={null} const userId = refine.getUserId(); // Returns 'user_12345' or null const visitorId = refine.getVisitorId(); // Always returns a value const sessionId = refine.getSessionId(); // Current session ID ``` ## User vs Visitor Recommendations | Aspect | Visitor Recs | User Recs | | -------------------- | ------------------- | ------------------------- | | **Data source** | Current device only | All devices, full history | | **Login required** | No | Yes | | **Purchase history** | Current session | All time | | **Cross-device** | No | Yes | | **Cold start** | More common | Less common | ## Tracking User Recommendations ```typescript theme={null} refine.identify('user_12345'); const recs = await refine.recs.forUser({ configId: 'personalized_picks', topK: 12 }); const recsContext = refine.events.trackRecommendations( recs.serveId, recs.results, 'home_page', 'user-recs' ); // Track interactions recsContext.trackClick(productId, position); recsContext.trackAddToCart(productId); ``` ## With Filters ```typescript theme={null} const recs = await refine.recs.forUser({ configId: 'personalized_picks', topK: 12, filters: [ { field: 'price', operator: 'lte', value: 200 }, { field: 'stock', operator: 'gt', value: 0 } ] }); ``` ## Complete Implementation ```typescript theme={null} import { Refine, RefineValidationError } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); class PersonalizedRecommendations { private isLoggedIn: boolean = false; async init(userId?: string) { if (userId) { refine.identify(userId); this.isLoggedIn = true; } } async getRecommendations(topK: number = 12) { if (this.isLoggedIn) { return this.getUserRecommendations(topK); } return this.getVisitorRecommendations(topK); } private async getUserRecommendations(topK: number) { try { const recs = await refine.recs.forUser({ configId: 'user_personalized', topK }); return { type: 'user', title: 'Picked for You', products: recs.results, context: refine.events.trackRecommendations( recs.serveId, recs.results, 'home_page', 'user-recs' ) }; } catch (error) { if (error instanceof RefineValidationError) { // User not properly identified, fall back to visitor console.warn('User recs failed, falling back to visitor'); return this.getVisitorRecommendations(topK); } throw error; } } private async getVisitorRecommendations(topK: number) { const recs = await refine.recs.forVisitor({ configId: 'visitor_homepage', topK }); return { type: 'visitor', title: 'Recommended for You', products: recs.results, context: refine.events.trackRecommendations( recs.serveId, recs.results, 'home_page', 'visitor-recs' ) }; } async handleLogout() { refine.reset(); this.isLoggedIn = false; } } // Usage const personalization = new PersonalizedRecommendations(); // On page load const currentUser = getCurrentUserFromSession(); // Your auth logic await personalization.init(currentUser?.id); // Get recommendations const { title, products, context } = await personalization.getRecommendations(12); // Render renderProductGrid(title, products, { onClick: (productId, position) => context.trackClick(productId, position), onAddToCart: (productId) => context.trackAddToCart(productId) }); ``` ## Handling Logout When a user logs out, reset the identity: ```typescript theme={null} function handleLogout() { // Clear user identity refine.reset(); // A new visitor ID will be generated for the next request // Previous behavior is no longer linked to this session } ``` ## Email/Marketing Recommendations Generate recommendations for email campaigns: ```typescript theme={null} // Server-side (e.g., email service integration) import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789', applicationType: 'server' }); async function getEmailRecommendations(userId: string) { refine.identify(userId); const recs = await refine.recs.forUser({ configId: 'email_personalized', topK: 6, filters: [ { field: 'stock', operator: 'gt', value: 0 } ] }); return recs.results.map(product => ({ title: product.title, price: product.price, imageUrl: product.imageUrl, productUrl: `https://store.com/products/${product.productId}` })); } ``` ## Fallback Strategy Handle new users with minimal history: ```typescript theme={null} async function getSmartRecommendations(userId: string | null) { if (!userId) { // Anonymous: visitor recommendations return refine.recs.forVisitor({ configId: 'popular', topK: 12 }); } refine.identify(userId); try { const userRecs = await refine.recs.forUser({ configId: 'personalized', topK: 12 }); if (userRecs.results.length >= 8) { return userRecs; } // Not enough personalized results, supplement with popular const popular = await refine.recs.forVisitor({ configId: 'popular', topK: 12 - userRecs.results.length }); return { ...userRecs, results: [...userRecs.results, ...popular.results] }; } catch { return refine.recs.forVisitor({ configId: 'popular', topK: 12 }); } } ``` ## Next Steps Full identity documentation Track user interactions # Visitor Recommendations Source: https://docs.joinrefine.io/sdk/recommendations/visitor-recommendations Personalized recommendations for anonymous visitors based on browsing behavior ## Overview Visitor recommendations personalize the shopping experience for anonymous users based on their current session behavior. No login required — Refine tracks visitors using automatically generated IDs stored in localStorage. ## Basic Usage ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); const recs = await refine.recs.forVisitor({ configId: 'homepage_personalized', topK: 12 }); recs.results.forEach(product => { console.log(`${product.title} - $${product.price}`); }); ``` ## Parameters Recommendation configuration ID from the dashboard. Defines the algorithm and business rules. Number of recommendations to return. Recommended: 8-24. Additional filters to apply. See [Filters](/sdk/search/filters). ## How Visitor Tracking Works The SDK automatically manages visitor identity: 1. **First Visit**: A unique `visitorId` is generated and stored in localStorage 2. **Subsequent Visits**: The same `visitorId` is reused 3. **Behavior Tracking**: Product views, clicks, and searches are associated with the visitor 4. **Recommendations**: The algorithm uses this history to personalize results ```typescript theme={null} // Check the current visitor ID const visitorId = refine.getVisitorId(); console.log('Visitor:', visitorId); // e.g., "v_a1b2c3d4e5" ``` Visitor IDs persist across sessions but not across devices or browsers. Use [User Recommendations](/sdk/recommendations/user-recommendations) for cross-device personalization. ## Creating Configurations Visitor recommendation configurations are created in the dashboard: **Dashboard → Recommendations → Configurations → New Configuration** Configuration options include: | Setting | Description | | ---------------- | ------------------------------------------------- | | **Strategy** | Collaborative filtering, content-based, or hybrid | | **Fallback** | What to show for new visitors with no history | | **Diversity** | How much to vary recommended categories | | **Recency Bias** | Weight recent behavior more heavily | | **Filters** | Default filters (e.g., in-stock only) | ## Tracking Visitor Recommendations ```typescript theme={null} const recs = await refine.recs.forVisitor({ configId: 'homepage_recs', topK: 12 }); const recsContext = refine.events.trackRecommendations( recs.serveId, recs.results, 'home_page', 'visitor-recs' ); // Track interactions recsContext.trackClick(productId, position); recsContext.trackView(productId, position); recsContext.trackAddToCart(productId); ``` ## With Filters Apply runtime filters on top of configuration defaults: ```typescript theme={null} const recs = await refine.recs.forVisitor({ configId: 'homepage_recs', topK: 12, filters: [ { field: 'price', operator: 'lte', value: 100 }, { field: 'metadata.category', operator: 'in', value: ['womens', 'accessories'] } ] }); ``` ## Use Cases ### Homepage Hero Show personalized picks based on browsing history: ```typescript theme={null} async function loadHomepageRecs() { const recs = await refine.recs.forVisitor({ configId: 'homepage_hero', topK: 8 }); return recs.results; } ``` ### Category Page Enhancement Mix algorithmic recommendations with category products: ```typescript theme={null} async function loadCategoryPageRecs(category: string) { const recs = await refine.recs.forVisitor({ configId: 'category_page_recs', topK: 8, filters: [ { field: 'metadata.category', operator: 'eq', value: category } ] }); return recs.results; } ``` ### Search Fallback When search returns no results, show personalized alternatives: ```typescript theme={null} async function handleEmptySearch(query: string) { const recs = await refine.recs.forVisitor({ configId: 'search_fallback', topK: 12 }); return { message: `No results for "${query}". You might like these:`, products: recs.results }; } ``` ### Exit Intent Show personalized recommendations in exit-intent popups: ```typescript theme={null} document.addEventListener('mouseleave', async (e) => { if (e.clientY < 0) { // Mouse leaving viewport at top const recs = await refine.recs.forVisitor({ configId: 'exit_intent', topK: 4 }); showExitPopup(recs.results); } }); ``` ## Complete Implementation ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); class HomepageRecommendations { private container: HTMLElement; private recsContext: any; constructor(containerId: string) { this.container = document.getElementById(containerId)!; this.load(); } private async load() { this.container.innerHTML = '

Loading recommendations...

'; try { const recs = await refine.recs.forVisitor({ configId: 'homepage_personalized', topK: 12 }); this.recsContext = refine.events.trackRecommendations( recs.serveId, recs.results, 'home_page', 'visitor-recs' ); this.render(recs.results); this.setupViewabilityTracking(); } catch (error) { this.container.innerHTML = '

Unable to load recommendations.

'; console.error('Recommendations error:', error); } } private render(products: any[]) { this.container.innerHTML = `

Recommended for You

${products.map((product, index) => `
${product.title}

${product.title}

$${product.price.toFixed(2)}

`).join('')}
`; // Click handlers this.container.querySelectorAll('.product-card').forEach(card => { const productId = (card as HTMLElement).dataset.id!; const position = parseInt((card as HTMLElement).dataset.position!); card.addEventListener('click', (e) => { if ((e.target as HTMLElement).classList.contains('add-to-cart')) { this.recsContext?.trackAddToCart(productId); } else { this.recsContext?.trackClick(productId, position); window.location.href = `/products/${productId}`; } }); }); } private setupViewabilityTracking() { const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const card = entry.target as HTMLElement; const productId = card.dataset.id!; const position = parseInt(card.dataset.position!); this.recsContext?.trackView(productId, position); observer.unobserve(card); } }); }, { threshold: 0.5 }); this.container.querySelectorAll('.product-card').forEach(card => { observer.observe(card); }); } } // Initialize new HomepageRecommendations('homepage-recs'); ``` ## New Visitor Handling For first-time visitors with no history, the configuration's fallback strategy kicks in: * **Popular Items**: Show best-sellers * **New Arrivals**: Show recently added products * **Editorial Picks**: Show curated selections Configure fallback behavior in the dashboard. ## Next Steps Personalization for logged-in users Product-based recommendations # Filters Source: https://docs.joinrefine.io/sdk/search/filters Filter operators and syntax for search and recommendations ## Overview Filters narrow search and recommendation results based on product attributes. Use filters for price ranges, categories, availability, and custom metadata. ## Basic Syntax ```typescript theme={null} const results = await refine.search.text({ query: 'summer dress', topK: 24, filters: [ { field: 'price', operator: 'lte', value: 200 } ] }); ``` Each filter has three properties: The product field to filter on. Use dot notation for nested metadata fields: `metadata.color`. The comparison operator. See [Operators](#operators) below. The value to compare against. Type depends on the operator. ## Operators ### Equality ```typescript theme={null} { field: 'metadata.brand', operator: 'eq', value: 'Nike' } ``` Exact match. Case-sensitive for strings. ```typescript theme={null} { field: 'metadata.brand', operator: 'ne', value: 'Generic' } ``` Excludes exact matches. ### Comparison ```typescript theme={null} { field: 'price', operator: 'gt', value: 50 } ``` Greater than (exclusive). ```typescript theme={null} { field: 'price', operator: 'gte', value: 50 } ``` Greater than or equal (inclusive). ```typescript theme={null} { field: 'price', operator: 'lt', value: 100 } ``` Less than (exclusive). ```typescript theme={null} { field: 'price', operator: 'lte', value: 100 } ``` Less than or equal (inclusive). ### Array Operators ```typescript theme={null} { field: 'metadata.color', operator: 'in', value: ['red', 'blue', 'green'] } ``` Field value is one of the provided values. ```typescript theme={null} { field: 'metadata.category', operator: 'nin', value: ['clearance', 'discontinued'] } ``` Field value is NOT one of the provided values. ### Existence ```typescript theme={null} { field: 'metadata.salePrice', operator: 'exists', value: true } ``` Check if a field exists (`true`) or doesn't exist (`false`). ### Text Matching ```typescript theme={null} { field: 'title', operator: 'match', value: 'organic' } ``` Partial text match within the field. Case-insensitive. ## Operator Reference | Operator | Description | Value Type | Example | | -------- | --------------------- | ---------- | -------------------------------------------------------------- | | `eq` | Equals | any | `{ field: 'brand', operator: 'eq', value: 'Nike' }` | | `ne` | Not equals | any | `{ field: 'status', operator: 'ne', value: 'discontinued' }` | | `gt` | Greater than | number | `{ field: 'price', operator: 'gt', value: 50 }` | | `gte` | Greater than or equal | number | `{ field: 'stock', operator: 'gte', value: 1 }` | | `lt` | Less than | number | `{ field: 'price', operator: 'lt', value: 100 }` | | `lte` | Less than or equal | number | `{ field: 'rating', operator: 'lte', value: 5 }` | | `in` | In array | array | `{ field: 'size', operator: 'in', value: ['S', 'M', 'L'] }` | | `nin` | Not in array | array | `{ field: 'tag', operator: 'nin', value: ['test'] }` | | `exists` | Field exists | boolean | `{ field: 'salePrice', operator: 'exists', value: true }` | | `match` | Text contains | string | `{ field: 'description', operator: 'match', value: 'cotton' }` | ## Common Patterns ### Price Range ```typescript theme={null} filters: [ { field: 'price', operator: 'gte', value: 50 }, { field: 'price', operator: 'lte', value: 200 } ] ``` ### In Stock Only ```typescript theme={null} filters: [ { field: 'stock', operator: 'gt', value: 0 } ] ``` ### Multiple Categories ```typescript theme={null} filters: [ { field: 'metadata.category', operator: 'in', value: ['dresses', 'skirts', 'tops'] } ] ``` ### Exclude Sale Items ```typescript theme={null} filters: [ { field: 'metadata.onSale', operator: 'ne', value: true } ] ``` ### Has Reviews ```typescript theme={null} filters: [ { field: 'metadata.reviewCount', operator: 'gte', value: 1 } ] ``` ### Brand Exclusion ```typescript theme={null} filters: [ { field: 'metadata.brand', operator: 'nin', value: ['Generic', 'Unknown'] } ] ``` ## Filter Logic Multiple filters are combined with **AND** logic. All conditions must be true for a product to be included. ```typescript theme={null} // Products where: // - price is between $50-$200 AND // - color is red, blue, or green AND // - in stock filters: [ { field: 'price', operator: 'gte', value: 50 }, { field: 'price', operator: 'lte', value: 200 }, { field: 'metadata.color', operator: 'in', value: ['red', 'blue', 'green'] }, { field: 'stock', operator: 'gt', value: 0 } ] ``` OR logic isn't directly supported. Use the `in` operator for "field equals A OR field equals B" scenarios. ## Metadata Fields Access nested metadata using dot notation: ```typescript theme={null} // Product structure { productId: 'sku_001', title: 'Summer Dress', price: 79.99, metadata: { brand: 'Fashion Co', color: 'red', sizes: ['S', 'M', 'L'], details: { material: 'cotton', origin: 'Italy' } } } // Filter examples { field: 'metadata.brand', operator: 'eq', value: 'Fashion Co' } { field: 'metadata.color', operator: 'in', value: ['red', 'blue'] } { field: 'metadata.details.material', operator: 'eq', value: 'cotton' } ``` ## Sorting Combine filters with sorting: ```typescript theme={null} const results = await refine.search.text({ query: 'shoes', topK: 24, filters: [ { field: 'price', operator: 'gte', value: 50 }, { field: 'stock', operator: 'gt', value: 0 } ], sortBy: { field: 'price', order: 'ascending' // 'ascending' | 'descending' } }); ``` Available sort fields depend on your catalog schema. Common options: * `price` * `metadata.rating` * `metadata.popularity` * `metadata.createdAt` Sorting by `relevance` (default) uses the AI ranking. Sorting by other fields overrides the AI ranking. ## Filter Options in Response Search responses include available filter values: ```typescript theme={null} const results = await refine.search.text({ query: 'dress', topK: 24 }); console.log(results.filterOptions); // [ // { field: 'metadata.color', values: ['red', 'blue', 'black', ...] }, // { field: 'metadata.size', values: ['XS', 'S', 'M', 'L', 'XL'] }, // { field: 'metadata.brand', values: ['Brand A', 'Brand B', ...] } // ] ``` Use this to build dynamic filter UIs: ```typescript theme={null} function buildFilterUI(filterOptions: FilterOption[]) { return filterOptions.map(option => `

${formatFieldName(option.field)}

${option.values.map(value => ` `).join('')}
`).join(''); } ``` ## Performance Tips * Filter on indexed fields for best performance * Use `in` with small arrays (under 100 values) * Avoid `match` on large text fields when possible * Combine price ranges into a single range filter ## Next Steps Search with text queries Filter recommendations too # Image Search Source: https://docs.joinrefine.io/sdk/search/image-search Search products by uploading an image to find visually similar items ## Overview Image search lets users find products by uploading a photo. Refine analyzes the image's visual features and returns products that look similar. Perfect for "shop the look" experiences, visual discovery, and reverse image search. ## Basic Usage ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); // With a File object (from file input) const fileInput = document.querySelector('input[type="file"]'); const file = fileInput.files[0]; const results = await refine.search.image({ image: file, topK: 12 }); ``` ## Image Input Formats The SDK accepts three image formats: ```typescript theme={null} // From file input const input = document.querySelector('#image-upload'); input.addEventListener('change', async (e) => { const file = input.files?.[0]; if (file) { const results = await refine.search.image({ image: file, topK: 12 }); } }); ``` ```typescript theme={null} // From canvas or fetch const canvas = document.querySelector('canvas'); canvas.toBlob(async (blob) => { const results = await refine.search.image({ image: blob, topK: 12 }); }); // From URL const response = await fetch('https://example.com/image.jpg'); const blob = await response.blob(); const results = await refine.search.image({ image: blob, topK: 12 }); ``` ```typescript theme={null} // From data URL const dataUrl = 'data:image/jpeg;base64,/9j/4AAQSkZJRg...'; const base64 = dataUrl.split(',')[1]; const results = await refine.search.image({ image: base64, topK: 12 }); ``` ## Parameters The image to search with. Accepts File objects, Blobs, or base64-encoded strings. Number of results to return. Recommended: 8-24 for image search. Array of filters to apply. See [Filters](/sdk/search/filters). ## With Filters Combine visual search with filters to narrow results: ```typescript theme={null} const results = await refine.search.image({ image: uploadedFile, topK: 20, filters: [ { field: 'price', operator: 'lte', value: 150 }, { field: 'metadata.category', operator: 'eq', value: 'dresses' }, { field: 'stock', operator: 'gt', value: 0 } ] }); ``` ## Response The response structure is identical to text search: ```typescript theme={null} interface SearchResponse { results: SearchResultItem[]; filterOptions?: FilterOption[]; serveId: string; totalResults: number; } interface SearchResultItem { productId: string; title: string; price: number; imageUrl: string; metadata: Record; score: number; // Visual similarity score } ``` ## Tracking Image Search Track image search results the same way as text search: ```typescript theme={null} const results = await refine.search.image({ image: file, topK: 12 }); const searchContext = refine.events.trackItemsServed({ surface: 'search_results', source: 'image-search', itemIds: results.results.map(r => r.productId), totalResults: results.totalResults }); // Track interactions searchContext.trackClick(productId, position); ``` ## Complete Implementation Here's a full drag-and-drop image search component: ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); class ImageSearchUploader { private dropzone: HTMLElement; private fileInput: HTMLInputElement; private resultsContainer: HTMLElement; private searchContext: any; constructor() { this.dropzone = document.getElementById('dropzone')!; this.fileInput = document.getElementById('file-input') as HTMLInputElement; this.resultsContainer = document.getElementById('results')!; this.setupEventListeners(); } private setupEventListeners() { // Drag and drop this.dropzone.addEventListener('dragover', (e) => { e.preventDefault(); this.dropzone.classList.add('drag-over'); }); this.dropzone.addEventListener('dragleave', () => { this.dropzone.classList.remove('drag-over'); }); this.dropzone.addEventListener('drop', async (e) => { e.preventDefault(); this.dropzone.classList.remove('drag-over'); const file = e.dataTransfer?.files[0]; if (file && file.type.startsWith('image/')) { await this.search(file); } }); // File input this.fileInput.addEventListener('change', async () => { const file = this.fileInput.files?.[0]; if (file) { await this.search(file); } }); } private async search(file: File) { this.resultsContainer.innerHTML = '

Searching...

'; try { const results = await refine.search.image({ image: file, topK: 16 }); // Track the search this.searchContext = refine.events.trackItemsServed({ surface: 'search_results', source: 'image-search', itemIds: results.results.map(r => r.productId), totalResults: results.totalResults }); this.renderResults(results.results); } catch (error) { this.resultsContainer.innerHTML = '

Search failed. Please try again.

'; console.error('Image search error:', error); } } private renderResults(products: SearchResultItem[]) { this.resultsContainer.innerHTML = products.map((product, index) => `
${product.title}

${product.title}

$${product.price.toFixed(2)}

Match: ${(product.score * 100).toFixed(0)}%

`).join(''); // Attach click handlers this.resultsContainer.querySelectorAll('.product').forEach(el => { el.addEventListener('click', () => { const productId = (el as HTMLElement).dataset.id!; const position = parseInt((el as HTMLElement).dataset.position!); this.searchContext?.trackClick(productId, position); }); }); } } // Initialize new ImageSearchUploader(); ``` ## Image Requirements For best results: | Requirement | Recommendation | | -------------- | ------------------------------- | | **Format** | JPEG, PNG, WebP | | **Size** | Max 10MB | | **Dimensions** | At least 200x200px | | **Quality** | Clear, well-lit images | | **Content** | Single product focus works best | Large images are resized server-side. For faster uploads, resize images to \~800px on the longest edge before sending. ## Use Cases Let users upload photos of outfits they like and find similar items in your catalog. Add a camera icon to your search bar for users who prefer visual browsing. Users can screenshot products from social media and find them in your store. Find similar products to items users found elsewhere (use responsibly). ## Error Handling ```typescript theme={null} import { RefineValidationError } from '@refine-ai/sdk'; try { const results = await refine.search.image({ image: file, topK: 12 }); } catch (error) { if (error instanceof RefineValidationError) { if (error.message.includes('file size')) { alert('Image too large. Please use an image under 10MB.'); } else if (error.message.includes('format')) { alert('Unsupported format. Please use JPEG, PNG, or WebP.'); } } } ``` ## Next Steps Search with text queries Filter operators reference # Text Search Source: https://docs.joinrefine.io/sdk/search/text-search Search products using natural language queries with visual similarity matching ## Overview Text search combines semantic text understanding with visual similarity to find relevant products. Use the `visualWeight` parameter to balance between text matching and visual similarity. ## Basic Usage ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); const results = await refine.search.text({ query: 'red running shoes', topK: 20 }); results.results.forEach(product => { console.log(`${product.title} - $${product.price}`); }); ``` ## Parameters The search query. Natural language queries like "summer dress for wedding" work best. Number of results to return. Recommended: 12-48 for grid layouts. Balance between text and visual search (0.0 to 1.0). * `0.0` = Pure text matching * `1.0` = Pure visual similarity * `0.3` = Text-primary with visual boost (default) Array of filters to apply. See [Filters](/sdk/search/filters) for operators. Sorting configuration with `field` and `order` ('ascending' | 'descending'). ## With Filters and Sorting ```typescript theme={null} const results = await refine.search.text({ query: 'summer dress', topK: 24, visualWeight: 0.5, filters: [ { field: 'price', operator: 'gte', value: 50 }, { field: 'price', operator: 'lte', value: 200 }, { field: 'metadata.color', operator: 'in', value: ['red', 'blue', 'green'] }, { field: 'stock', operator: 'gt', value: 0 } ], sortBy: { field: 'price', order: 'ascending' } }); ``` ## Response ```typescript theme={null} interface SearchResponse { results: SearchResultItem[]; filterOptions?: FilterOption[]; serveId: string; totalResults: number; } interface SearchResultItem { productId: string; title: string; price: number; imageUrl: string; metadata: Record; score: number; } ``` Array of matching products, ordered by relevance. Available filter values based on the result set. Useful for building faceted navigation. Unique identifier for this search serve. Used internally for event tracking. Total number of matching products (before `topK` limit). Use for pagination UI. ## Tracking Search Results Always track search results to power analytics and improve recommendations: ```typescript theme={null} const results = await refine.search.text({ query: 'shoes', topK: 20 }); const searchContext = refine.events.trackSearch( 'shoes', results.results, { surface: 'search_results', totalResults: results.totalResults } ); // When user clicks a product searchContext.trackClick(productId, position); // When a product becomes visible searchContext.trackView(productId, position); // When user adds to cart searchContext.trackAddToCart(productId); ``` See [Event Tracking](/sdk/events/overview) for more details. ## Visual Weight Recommendations The optimal `visualWeight` depends on your product category: | Category | Recommended Weight | Reason | | --------------- | ------------------ | ---------------------------- | | Fashion/Apparel | 0.5 - 0.7 | Visual appearance is primary | | Electronics | 0.2 - 0.4 | Specs and text matter more | | Home Goods | 0.4 - 0.6 | Balanced | | Art/Decor | 0.7 - 0.9 | Almost purely visual | | Books | 0.1 - 0.2 | Text is primary | | Jewelry | 0.6 - 0.8 | Visual details matter | A/B test different visual weights to find the optimal balance for your specific catalog and user behavior. ## Pagination Use `topK` with offset for pagination: ```typescript theme={null} const PAGE_SIZE = 24; let currentPage = 0; async function loadPage(page: number) { const results = await refine.search.text({ query: 'shoes', topK: PAGE_SIZE, // Note: offset is handled server-side with pagination tokens }); currentPage = page; return results; } ``` For best performance, prefer "Load More" patterns over traditional pagination. Each new search request is independent and provides fresh relevance scoring. ## Error Handling ```typescript theme={null} import { RefineValidationError, RefineAuthError, RefineRateLimitError } from '@refine-ai/sdk'; try { const results = await refine.search.text({ query: 'shoes', topK: 20 }); } catch (error) { if (error instanceof RefineValidationError) { console.error('Invalid search parameters:', error.message); } else if (error instanceof RefineAuthError) { console.error('Check your API key'); } else if (error instanceof RefineRateLimitError) { console.error('Rate limited, retry after:', error.retryAfter); } } ``` ## Complete Example ```typescript theme={null} import { Refine, RefineValidationError } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: 'org_abc123', catalogId: 'cat_xyz789' }); async function performSearch(query: string, filters: Filter[] = []) { try { const results = await refine.search.text({ query, topK: 24, visualWeight: 0.5, filters, sortBy: { field: 'relevance', order: 'descending' } }); // Track the search const searchContext = refine.events.trackSearch(query, results.results, { surface: 'search_results', totalResults: results.totalResults }); return { products: results.results, total: results.totalResults, filterOptions: results.filterOptions, trackClick: (productId: string, position: number) => { searchContext.trackClick(productId, position); } }; } catch (error) { if (error instanceof RefineValidationError) { return { products: [], total: 0, error: 'Invalid search' }; } throw error; } } ``` ## Next Steps Search using uploaded images Filter operators reference # Server-Side Usage Source: https://docs.joinrefine.io/sdk/server-side Use the Refine SDK in Node.js, serverless functions, and SSR frameworks ## Overview The Refine SDK works in server-side environments including Node.js, serverless functions (AWS Lambda, Vercel), and SSR frameworks (Next.js, Nuxt). ## Server Configuration ```typescript theme={null} import { Refine } from '@refine-ai/sdk'; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY, organizationId: process.env.REFINE_ORG_ID, catalogId: process.env.REFINE_CATALOG_ID, applicationType: 'server', events: { persistence: 'memory' // No localStorage on server } }); ``` Key differences from client-side: | Setting | Client | Server | | -------------------- | ---------------- | ---------- | | `applicationType` | `'web'` | `'server'` | | `events.persistence` | `'localStorage'` | `'memory'` | | Identity | Auto-managed | Explicit | ## Next.js ### Server Components (App Router) ```typescript theme={null} // app/search/page.tsx import { refine } from '@/lib/refine'; export default async function SearchPage({ searchParams }: { searchParams: { q?: string } }) { const query = searchParams.q || ''; if (!query) { return ; } const results = await refine.search.text({ query, topK: 24 }); return (
); } ``` ### API Routes ```typescript theme={null} // app/api/search/route.ts import { NextRequest, NextResponse } from 'next/server'; import { refine } from '@/lib/refine'; export async function GET(request: NextRequest) { const query = request.nextUrl.searchParams.get('q'); if (!query) { return NextResponse.json({ error: 'Query required' }, { status: 400 }); } try { const results = await refine.search.text({ query, topK: parseInt(request.nextUrl.searchParams.get('limit') || '24') }); return NextResponse.json(results); } catch (error) { console.error('Search error:', error); return NextResponse.json({ error: 'Search failed' }, { status: 500 }); } } ``` ### getServerSideProps (Pages Router) ```typescript theme={null} // pages/search.tsx import { refine } from '@/lib/refine'; import type { GetServerSideProps } from 'next'; export const getServerSideProps: GetServerSideProps = async (context) => { const query = context.query.q as string; if (!query) { return { props: { results: null, query: '' } }; } try { const results = await refine.search.text({ query, topK: 24 }); return { props: { results: results.results, totalResults: results.totalResults, query } }; } catch (error) { return { props: { results: [], query, error: 'Search failed' } }; } }; ``` ### Client-Side Hydration Server-render search results, then hydrate for interactivity: ```typescript theme={null} // lib/refine.ts import { Refine } from '@refine-ai/sdk'; // Server instance export const refine = new Refine({ apiKey: process.env.REFINE_API_KEY!, organizationId: process.env.REFINE_ORG_ID!, catalogId: process.env.REFINE_CATALOG_ID!, applicationType: 'server', events: { persistence: 'memory' } }); // Client instance (created dynamically) export function createClientRefine() { return new Refine({ apiKey: process.env.NEXT_PUBLIC_REFINE_API_KEY!, organizationId: process.env.NEXT_PUBLIC_REFINE_ORG_ID!, catalogId: process.env.NEXT_PUBLIC_REFINE_CATALOG_ID!, applicationType: 'web' }); } ``` ```tsx theme={null} // components/SearchResults.tsx 'use client'; import { useEffect, useState } from 'react'; import { createClientRefine } from '@/lib/refine'; export function SearchResults({ initialResults, query }: { initialResults: any[]; query: string; }) { const [refine] = useState(() => createClientRefine()); useEffect(() => { // Track the search on client if (initialResults.length > 0) { const context = refine.events.trackSearch(query, initialResults, { surface: 'search_results', totalResults: initialResults.length }); // Set up click tracking // ... } }, [query, initialResults]); return (
{initialResults.map((product, index) => ( ))}
); } ``` ## AWS Lambda ```typescript theme={null} // handler.ts import { Refine } from '@refine-ai/sdk'; // Initialize outside handler for connection reuse const refine = new Refine({ apiKey: process.env.REFINE_API_KEY!, organizationId: process.env.REFINE_ORG_ID!, catalogId: process.env.REFINE_CATALOG_ID!, applicationType: 'server', events: { persistence: 'memory' } }); export const handler = async (event: any) => { const query = event.queryStringParameters?.q; if (!query) { return { statusCode: 400, body: JSON.stringify({ error: 'Query required' }) }; } try { const results = await refine.search.text({ query, topK: 24 }); return { statusCode: 200, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(results) }; } catch (error) { console.error('Search error:', error); return { statusCode: 500, body: JSON.stringify({ error: 'Search failed' }) }; } }; ``` ## Vercel Edge Functions ```typescript theme={null} // api/search.ts import { Refine } from '@refine-ai/sdk'; export const config = { runtime: 'edge' }; const refine = new Refine({ apiKey: process.env.REFINE_API_KEY!, organizationId: process.env.REFINE_ORG_ID!, catalogId: process.env.REFINE_CATALOG_ID!, applicationType: 'server', events: { persistence: 'memory' } }); export default async function handler(request: Request) { const url = new URL(request.url); const query = url.searchParams.get('q'); if (!query) { return new Response(JSON.stringify({ error: 'Query required' }), { status: 400, headers: { 'Content-Type': 'application/json' } }); } const results = await refine.search.text({ query, topK: 24 }); return new Response(JSON.stringify(results), { headers: { 'Content-Type': 'application/json' } }); } ``` ## Identity on Server On the server, you need to manage identity explicitly: ```typescript theme={null} // For user-based recommendations export async function getUserRecommendations(userId: string) { refine.identify(userId); const recs = await refine.recs.forUser({ configId: 'personalized', topK: 12 }); return recs; } // For server-side purchase tracking export async function trackPurchase(userId: string, order: Order) { refine.identify(userId); refine.events.trackPurchase({ orderId: order.id, value: order.total, currency: order.currency, items: order.items.map(item => ({ itemId: item.productId, quantity: item.quantity, unitPrice: item.unitPrice })) }); await refine.events.flush(); } ``` ## Caching Recommendations Cache recommendations for performance: ```typescript theme={null} import { LRUCache } from 'lru-cache'; const recsCache = new LRUCache({ max: 500, ttl: 1000 * 60 * 5 // 5 minutes }); export async function getCachedSimilarItems(productId: string) { const cacheKey = `similar:${productId}`; let results = recsCache.get(cacheKey); if (results) { return results; } results = await refine.recs.similarItems({ anchorId: productId, topK: 8 }); recsCache.set(cacheKey, results); return results; } ``` ## Error Handling on Server ```typescript theme={null} import { RefineRateLimitError, RefineServerError } from '@refine-ai/sdk'; export async function handleSearchRequest(query: string) { try { return await refine.search.text({ query, topK: 24 }); } catch (error) { if (error instanceof RefineRateLimitError) { // Return 429 to let client handle retry throw { status: 429, retryAfter: error.retryAfter }; } if (error instanceof RefineServerError) { // Log and return graceful error console.error('Refine server error:', error); throw { status: 503, message: 'Search temporarily unavailable' }; } throw error; } } ``` ## Testing Mock the SDK for tests: ```typescript theme={null} // __mocks__/@refine-ai/sdk.ts export class Refine { search = { text: jest.fn().mockResolvedValue({ results: [ { productId: 'sku_001', title: 'Test Product', price: 99.99 } ], totalResults: 1 }) }; recs = { similarItems: jest.fn().mockResolvedValue({ results: [] }), forVisitor: jest.fn().mockResolvedValue({ results: [] }), forUser: jest.fn().mockResolvedValue({ results: [] }) }; events = { trackSearch: jest.fn(), trackPurchase: jest.fn(), flush: jest.fn() }; identify = jest.fn(); } ``` ## Next Steps Client-side React patterns Handle server-side errors