Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.tybritelabs.com/llms.txt

Use this file to discover all available pages before exploring further.

The Tybrite TypeScript SDK provides a high-level, type-safe interface for interacting with the Tybrite API. It simplifies complex operations like order processing, inventory management, and customer analytics into easy-to-use methods.

Installation

Install the SDK using your preferred package manager. npm will always resolve to the latest published version.
npm install @tybrite-labs/sdk

Quick Start

To begin using the SDK, you need to initialize the Tybrite client with your API key.
import { Tybrite } from '@tybrite-labs/sdk';

const client = new Tybrite({
  apiKey: 'tybrite_pk_live_your_key_here',
});

Configuration Options

The Tybrite constructor accepts a configuration object to customize the client behavior:
PropertyTypeDescription
apiKeystringYour Tybrite API key (Publishable or Secret).
BASEstringOptional. The base URL of the API. Defaults to https://api.tybritelabs.com.
HEADERSRecord<string, string>Optional. Custom headers to be included in every request.

Two-Token Security Model

The Tybrite API uses two parallel authentication mechanisms. Most endpoints need only the API key, but customer-scoped operations require both a publishable API key (to identify your store) and a customer session token (to identify the shopper).
  1. API key (Authorization header) — authenticates your application
    • Publishable keys (tybrite_pk_*) — safe for browsers; read-only for sensitive data
    • Secret keys (tybrite_sk_*) — server-side only; full read/write access
  2. Customer session token (xAuthToken parameter) — authenticates an end customer
    • Obtained from client.authentication.login, verifyOtp, or register
    • Required for customer-scoped operations (cart, wishlist, profile, gift cards, messaging)
    • The resolved customer must match the customer_id in the request, otherwise the API returns 403
Customer write operations on cart and wishlist intentionally accept publishable keys, so browser code can call them directly. The xAuthToken is what proves the request belongs to a specific shopper.

Combining both tokens

import { Tybrite } from '@tybrite-labs/sdk';

// 1. Initialize with API key
const client = new Tybrite({ apiKey: 'tybrite_pk_live_...' });

// 2. Authenticate the customer (returns a session token)
const { session } = await client.authentication.login({
  requestBody: { email: 'jane@example.com', password: '...' }
});

// 3. Use the session token for customer-scoped calls
const cart = await client.cartWishlist.getCart({
  customerId: session.customer.id,
  xAuthToken: session.access_token,  // <-- customer JWT
});

// 4. Anonymous operations don't need xAuthToken
const products = await client.products.listProducts();
Never embed secret keys (tybrite_sk_*) in browser bundles, mobile apps, or any client-side environment. Use publishable keys in clients and reserve secret keys for trusted server-side processes.

Basic Usage

Once initialized, you can access various commerce services through the client instance.
// List products
const response = await client.products.listProducts({
  limit: 20
});

console.log(response.products);

Response Codes

Every service in the SDK follows the same response-code contract, so you can centralize your error handling:
CodeWhen
200Successful GET, PATCH, or DELETE
201POST that creates a new resource (orders, customers, register, addToWishlist, payment init, messaging threads/messages)
400Invalid request body, missing required field, invalid UUID/slug, or invalid query parameter
401Missing or invalid API key or customer JWT
403Valid auth but wrong key type for the operation, OR customer JWT does not match the customer_id in the request
404Resource not found by id/slug, OR a referenced resource (e.g. product_id on an order) is missing
409Uniqueness conflict (duplicate email on register/customer, duplicate wishlist item, idempotency key reused with a different body)
429Rate limit exceeded
500Server error
All errors share a single response shape:
{
  "error": {
    "code": "string",
    "message": "string",
    "details": "optional string"
  }
}
The SDK surfaces these as a typed ApiError you can catch:
import { ApiError } from '@tybrite-labs/sdk';

try {
  await client.orders.createOrder({ requestBody: order });
} catch (err) {
  if (err instanceof ApiError && err.status === 409) {
    // Idempotency replay with a different body, or duplicate resource
  }
  throw err;
}

Post-Processing Warnings on Orders

Order creation may include a post_processing_warnings array in the response when gift card redemption or stock reduction partially fails. The order is still recorded — clients should check this array and surface warnings to customers or operators. See the OrdersService docs for details.
const result = await client.orders.createOrder({
  idempotencyKey: crypto.randomUUID(),
  requestBody: order,
});

if (result.post_processing_warnings?.length) {
  for (const warning of result.post_processing_warnings) {
    console.warn('[order warning]', warning);
  }
}

Cursor-Based Pagination

For high-performance, stable scrolling through large datasets, Tybrite uses cursor-based pagination. This ensures consistent results even if data changes between requests. When a query supports cursor pagination, it will return a pagination object along with the results. You can pass the next_cursor property to subsequent requests to fetch the next page:
// 1. Fetch the first page
const page1 = await client.products.listProducts({ limit: 20 });

// 2. Check if there's more data
if (page1.pagination.has_more) {
  // 3. Fetch the next page using the cursor
  const page2 = await client.products.listProducts({
    limit: 20,
    cursor: page1.pagination.next_cursor
  });
}
The following services currently support cursor-based pagination:

Service Overview

The SDK exposes 16 services, each accessible as a property on the Tybrite client. The “Customer auth?” column indicates whether the customer session token (xAuthToken) is required for at least some methods.
ServiceAccess viaCustomer auth?Purpose
authenticationclient.authenticationIssues tokensCustomer login, OTP, registration, password reset
productsclient.productsNoProduct catalog, variants, specifications, collections
taxonomyclient.taxonomyNoCategories and subcategories
pricingclient.pricingNoDynamic pricing engine and quotes
cartWishlistclient.cartWishlistYes (when customer_id provided)Persistent cart and wishlist for sessions or customers
customersclient.customersYes (on get/update)Customer profile create, read, update
ordersclient.ordersNo (secret-key only)Order lifecycle, status transitions, idempotent creation
paymentsclient.paymentsNo (secret-key writes)Stripe, Paystack, M-Pesa, Airtel — init and confirm
giftCardsclient.giftCardsYes (when listing for a customer)Issue, redeem, and look up gift card balances
promotionsclient.promotionsNoDiscount rules and usage tracking
messagingclient.messagingYes (all customer-scoped routes)Customer-to-store conversation threads and messages
cmsclient.cmsNoBlog posts and shoppable lookbooks
shippingclient.shippingNoDelivery zones and distance-based rate quotes
recommendationsclient.recommendationsNoHybrid AI: Gemini embeddings + collaborative filtering
searchclient.searchNoSemantic search with text fallback
systemclient.systemNoHealth checks and store metadata

Next Steps

Now that you have initialized the client, explore the most commonly used services:

Products

Manage your product catalog, categories, and inventory.

Orders

Handle the full lifecycle of commerce orders.

Customers

Manage customer profiles and analytics.

Authentication

Secure customer sessions and authentication flows.

Cart & Wishlist

Persistent cart and wishlist tied to customer sessions.

System & Store

Monitor health status and retrieve comprehensive store metadata.