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 to set one up via API, or use the dashboard.
Install the SDK
npm install @refine-ai/sdk
Initialize the Client
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
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:
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) => `
<div class="product" data-id="${product.productId}" data-position="${index}">
<img src="${product.imageUrl}" alt="${product.title}" />
<h3>${product.title}</h3>
<p>$${product.price}</p>
</div>
`).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:
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?