Headless Core SDK
Package: @rebuy/[email protected]
npm: npmjs.com/package/@rebuy/core-sdk
The framework-agnostic core SDK for Rebuy's personalization and recommendation engine. This lightweight, TypeScript-first library provides the foundational data layer for building personalized e-commerce experiences.
Table of Contents
Installation
npm install @rebuy/core-sdk
Quick Start
import { RebuySDK } from '@rebuy/core-sdk';
// Initialize the SDK
const sdk = new RebuySDK({
apiKey: 'your-api-key',
});
// Fetch top seller recommendations
const topSellers = await sdk.products.getTopSellers({ limit: 5 });
console.log('Top Sellers:', topSellers);
// Fetch recommendations from a custom Data Source
const dataSourceProducts = await sdk.products.fetchFromDataSource(1234, {
shopify_product_ids: ['product-123'],
limit: 6,
});
console.log('Products from Data Source:', dataSourceProducts);
Core Features
Product Recommendations
Fetch product recommendations from any of Rebuy's standard endpoints or from a custom Data Source.
Standard Recommendations:
// Get top sellers
const topSellers = await sdk.products.getTopSellers({ limit: 10 });
// Get similar products
const similarProducts = await sdk.products.getSimilar({ limit: 5 });
Custom Data Sources:
Leverage the full power of the Rebuy rules engine by fetching from a specific Data Source.
const products = await sdk.products.fetchFromDataSource(1234, {
cart: currentCartObject,
limit: 4,
});
Context Builder
The RebuyContextBuilder class provides a fluent API for creating rich context objects for Data Sources. This reduces errors and improves discoverability of context parameters.
import { RebuyContextBuilder } from '@rebuy/core-sdk';
// Create a context with the builder
const context = new RebuyContextBuilder(sdk)
.withCart(cartObject)
.withProduct({ id: 'gid://shopify/Product/123' })
.withCustomer({ id: 456, tags: ['vip', 'wholesale'] })
.withUrl('https://shop.com/products?sort=price')
.withLocation('US')
.withLanguage('en')
.build();
// Use the context with a Data Source
const products = await sdk.products.fetchFromDataSource('pdp-recommendations', context);
Builder Methods:
merge(context) - Merge an existing context object
withCart(cart) - Add cart data using the SDK's internal transformer
withProduct(product) - Add a product's ID (can be chained for multiple products)
withCustomer(customer) - Add customer ID and tags
withUrl(url) - Extract path and query parameters from a URL
withLocation(countryCode) - Add the user's country code (ISO 3166-1 alpha-2)
withLanguage(language) - Add the user's language code (ISO 639-1)
build() - Return the final context object
Viewed Products
Track and retrieve products that users have viewed.
// Track a product view
await sdk.tracking.productView('product-123');
// Get recently viewed products
const viewedProducts = await sdk.products.getRecentlyViewed({ limit: 10 });
API Reference
RebuySDK
Constructor Options
| Option |
Type |
Required |
Description |
apiKey |
string |
✅ |
Your Rebuy API key |
apiHost |
string |
❌ |
API host URL (defaults to 'https://rebuyengine.com') |
debug |
boolean |
❌ |
Enable debug logging (defaults to false) |
Modules
sdk.products
getRecentlyViewed(options): Promise<Product[]> - Get recently viewed products.
getRecommended(options): Promise<Product[]> - Get recommended products.
getTopSellers(options): Promise<Product[]> - Get top selling products.
getTrending(options): Promise<Product[]> - Get trending products.
getPurchased(options): Promise<Product[]> - Get previously purchased products.
getCollections(body): Promise<Product[]> - Get products from a list of collections.
getStatic(options): Promise<Product[]> - Get a static list of products.
getSimilar(options): Promise<Product[]> - Get similar products.
fetchFromDataSource(dataSourceId, context): Promise<Product[]> - Fetch products from a custom Data Source.
sdk.tracking
productView(productId: string): Promise<void> - Track a product view event.
sdk.cart
get(): Promise<ShopifyCart> - Get current cart from Shopify.
createDataSourceContext(cart): RebuyCartContext - Transform a cart object into a context for Data Sources.
Note: The cart module is intentionally read-only. Cart mutations should be handled through your existing cart system (e.g., Shopify's Cart API). This design allows the SDK to read cart state for features like recommendations and GWP rules without prescribing how cart operations should be implemented.
RebuyContextBuilder
The RebuyContextBuilder class provides a fluent API for creating context objects:
const builder = new RebuyContextBuilder(sdk);
Methods
merge(context: Partial<RebuyCartContext>): this - Merge an existing context object
withCart(cart: SupportedCart): this - Add cart data using the SDK's internal transformer
withProduct(product: { id: string }): this - Add a product's ID (chainable)
withCustomer(customer: { id: string | number; tags?: string[] }): this - Add customer data
withUrl(url: string | URL): this - Extract URL path and parameters
withLocation(countryCode: string): this - Add country code (ISO 3166-1 alpha-2)
withLanguage(language: string): this - Add language code (ISO 639-1)
build(): RebuyCartContext - Return the final context object
Configuration
const sdk = new RebuySDK({
apiKey: 'your-api-key',
debug: process.env.NODE_ENV === 'development',
});
Error Handling
try {
const products = await sdk.products.getTopSellers({ limit: 5 });
} catch (error) {
console.error('SDK Error:', error.message);
}
TypeScript Support
This SDK is built with TypeScript and provides full type safety.
import type { Product } from '@rebuy/core-sdk';
const products: Product[] = await sdk.products.getTopSellers({ limit: 5 });
Framework Integration
While this is a framework-agnostic SDK, we provide first-party integrations:
Usage with React/Hydrogen
For React and Shopify Hydrogen projects, we recommend using our dedicated wrapper, @rebuy/hydrogen-sdk.
npm install @rebuy/hydrogen-sdk
See the @rebuy/hydrogen-sdk documentation for detailed usage instructions.
---
title: Headless Core SDK
excerpt: >
Core SDK for Rebuy headless integrations. Framework-agnostic foundation for recommendations, cart, and analytics.
---
<!--
Auto-generated from @rebuy/[email protected]
Do not edit directly - run: python scripts/sync-headless-docs.py
-->
# Headless Core SDK
> **Package:** `@rebuy/[email protected]`
> **npm:** [npmjs.com/package/@rebuy/core-sdk](https://www.npmjs.com/package/@rebuy/core-sdk)
The framework-agnostic core SDK for Rebuy's personalization and recommendation engine. This lightweight, TypeScript-first library provides the foundational data layer for building personalized e-commerce experiences.
## Table of Contents
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Core Features](#core-features)
- [API Reference](#api-reference)
- [Configuration](#configuration)
- [Error Handling](#error-handling)
- [TypeScript Support](#typescript-support)
## Installation
```bash
npm install @rebuy/core-sdk
```
## Quick Start
```typescript
import { RebuySDK } from '@rebuy/core-sdk';
// Initialize the SDK
const sdk = new RebuySDK({
apiKey: 'your-api-key',
});
// Fetch top seller recommendations
const topSellers = await sdk.products.getTopSellers({ limit: 5 });
console.log('Top Sellers:', topSellers);
// Fetch recommendations from a custom Data Source
const dataSourceProducts = await sdk.products.fetchFromDataSource(1234, {
shopify_product_ids: ['product-123'],
limit: 6,
});
console.log('Products from Data Source:', dataSourceProducts);
```
## Core Features
### Product Recommendations
Fetch product recommendations from any of Rebuy's standard endpoints or from a custom Data Source.
**Standard Recommendations:**
```typescript
// Get top sellers
const topSellers = await sdk.products.getTopSellers({ limit: 10 });
// Get similar products
const similarProducts = await sdk.products.getSimilar({ limit: 5 });
```
**Custom Data Sources:**
Leverage the full power of the Rebuy rules engine by fetching from a specific Data Source.
```typescript
const products = await sdk.products.fetchFromDataSource(1234, {
cart: currentCartObject,
limit: 4,
});
```
### Context Builder
The `RebuyContextBuilder` class provides a fluent API for creating rich context objects for Data Sources. This reduces errors and improves discoverability of context parameters.
```typescript
import { RebuyContextBuilder } from '@rebuy/core-sdk';
// Create a context with the builder
const context = new RebuyContextBuilder(sdk)
.withCart(cartObject)
.withProduct({ id: 'gid://shopify/Product/123' })
.withCustomer({ id: 456, tags: ['vip', 'wholesale'] })
.withUrl('https://shop.com/products?sort=price')
.withLocation('US')
.withLanguage('en')
.build();
// Use the context with a Data Source
const products = await sdk.products.fetchFromDataSource('pdp-recommendations', context);
```
**Builder Methods:**
- `merge(context)` - Merge an existing context object
- `withCart(cart)` - Add cart data using the SDK's internal transformer
- `withProduct(product)` - Add a product's ID (can be chained for multiple products)
- `withCustomer(customer)` - Add customer ID and tags
- `withUrl(url)` - Extract path and query parameters from a URL
- `withLocation(countryCode)` - Add the user's country code (ISO 3166-1 alpha-2)
- `withLanguage(language)` - Add the user's language code (ISO 639-1)
- `build()` - Return the final context object
### Viewed Products
Track and retrieve products that users have viewed.
```typescript
// Track a product view
await sdk.tracking.productView('product-123');
// Get recently viewed products
const viewedProducts = await sdk.products.getRecentlyViewed({ limit: 10 });
```
## API Reference
### RebuySDK
#### Constructor Options
| Option | Type | Required | Description |
| --------- | --------- | -------- | ---------------------------------------------------- |
| `apiKey` | `string` | ✅ | Your Rebuy API key |
| `apiHost` | `string` | ❌ | API host URL (defaults to 'https://rebuyengine.com') |
| `debug` | `boolean` | ❌ | Enable debug logging (defaults to false) |
### Modules
#### `sdk.products`
- `getRecentlyViewed(options): Promise<Product[]>` - Get recently viewed products.
- `getRecommended(options): Promise<Product[]>` - Get recommended products.
- `getTopSellers(options): Promise<Product[]>` - Get top selling products.
- `getTrending(options): Promise<Product[]>` - Get trending products.
- `getPurchased(options): Promise<Product[]>` - Get previously purchased products.
- `getCollections(body): Promise<Product[]>` - Get products from a list of collections.
- `getStatic(options): Promise<Product[]>` - Get a static list of products.
- `getSimilar(options): Promise<Product[]>` - Get similar products.
- `fetchFromDataSource(dataSourceId, context): Promise<Product[]>` - Fetch products from a custom Data Source.
#### `sdk.tracking`
- `productView(productId: string): Promise<void>` - Track a product view event.
#### `sdk.cart`
- `get(): Promise<ShopifyCart>` - Get current cart from Shopify.
- `createDataSourceContext(cart): RebuyCartContext` - Transform a cart object into a context for Data Sources.
**Note:** The cart module is intentionally read-only. Cart mutations should be handled through your existing cart system (e.g., Shopify's Cart API). This design allows the SDK to read cart state for features like recommendations and GWP rules without prescribing how cart operations should be implemented.
### RebuyContextBuilder
The `RebuyContextBuilder` class provides a fluent API for creating context objects:
```typescript
const builder = new RebuyContextBuilder(sdk);
```
#### Methods
- `merge(context: Partial<RebuyCartContext>): this` - Merge an existing context object
- `withCart(cart: SupportedCart): this` - Add cart data using the SDK's internal transformer
- `withProduct(product: { id: string }): this` - Add a product's ID (chainable)
- `withCustomer(customer: { id: string | number; tags?: string[] }): this` - Add customer data
- `withUrl(url: string | URL): this` - Extract URL path and parameters
- `withLocation(countryCode: string): this` - Add country code (ISO 3166-1 alpha-2)
- `withLanguage(language: string): this` - Add language code (ISO 639-1)
- `build(): RebuyCartContext` - Return the final context object
## Configuration
```typescript
const sdk = new RebuySDK({
apiKey: 'your-api-key',
debug: process.env.NODE_ENV === 'development',
});
```
## Error Handling
```typescript
try {
const products = await sdk.products.getTopSellers({ limit: 5 });
} catch (error) {
console.error('SDK Error:', error.message);
}
```
## TypeScript Support
This SDK is built with TypeScript and provides full type safety.
```typescript
import type { Product } from '@rebuy/core-sdk';
const products: Product[] = await sdk.products.getTopSellers({ limit: 5 });
```
## Framework Integration
While this is a framework-agnostic SDK, we provide first-party integrations:
- **React/Shopify Hydrogen**: [`@rebuy/hydrogen-sdk`](https://www.npmjs.com/package/@rebuy/hydrogen-sdk)
### Usage with React/Hydrogen
For React and Shopify Hydrogen projects, we recommend using our dedicated wrapper, `@rebuy/hydrogen-sdk`.
```bash
npm install @rebuy/hydrogen-sdk
```
See the [`@rebuy/hydrogen-sdk` documentation](https://www.npmjs.com/package/@rebuy/hydrogen-sdk) for detailed usage instructions.