# 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.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.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.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) => `
);
}
```
## 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 Title
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.price}
))}
);
}
```
### Vue
```vue theme={null}
{{ product.title }}
${{ product.price }}
```
## 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}
We value your privacy
We use cookies and similar technologies to personalize your experience
and analyze site usage. By clicking "Accept All", you consent to our
use of cookies.
```
## 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