> ## 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.

# Introduction

> Get started with the Tybrite TypeScript SDK for building commerce applications.

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.

<CodeGroup>
  ```bash npm theme={null}
  npm install @tybrite-labs/sdk
  ```

  ```bash yarn theme={null}
  yarn add @tybrite-labs/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @tybrite-labs/sdk
  ```
</CodeGroup>

## Quick Start

To begin using the SDK, you need to initialize the `Tybrite` client with your API key.

```typescript theme={null}
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:

| Property         | Type                     | Description                                                                                                           |
| :--------------- | :----------------------- | :-------------------------------------------------------------------------------------------------------------------- |
| `apiKey`         | `string`                 | Your Tybrite API key (Publishable or Secret).                                                                         |
| `BASE`           | `string`                 | Optional. The base URL of the API. Defaults to `https://api.tybritelabs.com`.                                         |
| `HEADERS`        | `Record<string, string>` | Optional. Custom headers to be included in every request.                                                             |
| `MAX_RETRIES`    | `number`                 | Optional. Maximum number of automatic retries for transient failures. Defaults to `2`. Set to `0` to disable retries. |
| `RETRY_DELAY_MS` | `number`                 | Optional. Base delay (ms) for exponential backoff between retries. Defaults to `500`.                                 |

## Automatic Retries

The SDK automatically retries requests that fail for transient reasons — network errors and the
HTTP statuses `429`, `500`, `502`, `503`, and `504` — using exponential backoff with jitter
(and honoring a `Retry-After` header when the API sends one). By default it makes up to **2**
retries; tune or disable this with `MAX_RETRIES`.

```typescript theme={null}
const client = new Tybrite({
  apiKey: 'tybrite_sk_live_...',
  MAX_RETRIES: 3,      // up to 3 retries (4 attempts total)
  RETRY_DELAY_MS: 400, // ~0.4s, 0.8s, 1.6s (+ jitter)
});
```

**Retries are safe by design.** The SDK never risks creating a duplicate resource:

* `GET`, `PUT`, and `DELETE` are safe to repeat and are always retried.
* `POST` and `PATCH` are retried on an error **status** only when you send an
  `Idempotency-Key` header. The API deduplicates those operations server-side
  (order creation, order updates, and payment initialization), so a retry returns the
  original result instead of acting twice. A `POST`/`PATCH` without an idempotency key is
  retried only when the connection fails outright (the request never reached the server, so
  no work could have happened) — never after the server has responded.

<Tip>
  For order and payment calls, always pass a unique `Idempotency-Key`. It both guarantees
  exactly-once processing and unlocks automatic retries for those requests.
</Tip>

## 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`

<Tip>
  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.
</Tip>

### Combining both tokens

```typescript theme={null}
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();
```

<Warning>
  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.
</Warning>

## Basic Usage

Once initialized, you can access various commerce services through the client instance.

```typescript theme={null}
// 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:

| Code  | When                                                                                                                                                                                |
| :---- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `200` | Successful `GET`, `PATCH`, or `DELETE`                                                                                                                                              |
| `201` | `POST` that creates a new resource (orders, customers, register, addToWishlist, payment init, messaging threads/messages)                                                           |
| `400` | Invalid request body, missing required field, invalid UUID/slug, or invalid query parameter                                                                                         |
| `401` | Missing or invalid API key or customer JWT                                                                                                                                          |
| `403` | Valid auth but wrong key type for the operation, OR customer JWT does not match the `customer_id` in the request                                                                    |
| `404` | Resource not found by id/slug, OR a referenced resource (e.g. `product_id` on an order) is missing                                                                                  |
| `409` | Uniqueness conflict (duplicate email on register/customer, duplicate wishlist item, idempotency key reused with a different body)                                                   |
| `429` | Too many requests — `rate_limited` (abuse throttle; carries `X-RateLimit-Scope: abuse`, not counted against the monthly quota) or `quota_exceeded` (monthly plan allowance reached) |
| `500` | Server error                                                                                                                                                                        |

All errors share a single response shape:

```json theme={null}
{
  "error": {
    "code": "string",
    "message": "string",
    "details": "optional string"
  }
}
```

The SDK surfaces these as a typed `ApiError` you can `catch`:

```typescript theme={null}
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

<Note>
  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](/sdk/api-reference/classes/OrdersService) for details.
</Note>

```typescript theme={null}
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:

```typescript theme={null}
// 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:

* [Products](/sdk/api-reference/classes/ProductsService)
* [Taxonomy](/sdk/api-reference/classes/TaxonomyService)
* [Promotions](/sdk/api-reference/classes/PromotionsService)
* [CMS](/sdk/api-reference/classes/CmsService)
* [Messaging](/sdk/api-reference/classes/MessagingService)

## Service Overview

The SDK exposes 17 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.

| Service           | Access via               | Customer auth?                    | Purpose                                                                                                                                                                                                          |
| :---------------- | :----------------------- | :-------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `authentication`  | `client.authentication`  | Issues tokens                     | Customer login, OTP, registration, password reset                                                                                                                                                                |
| `products`        | `client.products`        | No                                | Product catalog, variants, specifications, collections                                                                                                                                                           |
| `taxonomy`        | `client.taxonomy`        | No                                | Categories and subcategories                                                                                                                                                                                     |
| `pricing`         | `client.pricing`         | No                                | Dynamic pricing engine and quotes                                                                                                                                                                                |
| `cartWishlist`    | `client.cartWishlist`    | Yes (when `customer_id` provided) | Persistent cart and wishlist for sessions or customers                                                                                                                                                           |
| `customers`       | `client.customers`       | Yes (on get/update)               | Customer profile create, read, update                                                                                                                                                                            |
| `orders`          | `client.orders`          | No (secret-key only)              | Order lifecycle — list/browse, retrieve, idempotent creation, status transitions                                                                                                                                 |
| `payments`        | `client.payments`        | No (secret-key writes)            | Stripe, PayPal, Paystack, M-Pesa — init and confirm                                                                                                                                                              |
| `giftCards`       | `client.giftCards`       | Yes (when listing for a customer) | Issue, redeem, and look up gift card balances                                                                                                                                                                    |
| `promotions`      | `client.promotions`      | No                                | Discount rules and usage tracking                                                                                                                                                                                |
| `messaging`       | `client.messaging`       | Yes (all customer-scoped routes)  | Customer-to-store conversation threads and messages                                                                                                                                                              |
| `cms`             | `client.cms`             | No                                | Blog posts and shoppable lookbooks                                                                                                                                                                               |
| `shipping`        | `client.shipping`        | No                                | Delivery zones and distance-based rate quotes                                                                                                                                                                    |
| `recommendations` | `client.recommendations` | No                                | Hybrid AI: vector embeddings + collaborative filtering                                                                                                                                                           |
| `search`          | `client.search`          | No                                | Semantic search with text fallback                                                                                                                                                                               |
| `analytics`       | `client.analytics`       | No                                | First-party storefront analytics capture (page views / sessions) powering the merchant's traffic, funnel, and revenue reporting                                                                                  |
| `marketplace`     | `client.marketplace`     | Yes (unified profile)             | Multi-merchant marketplaces — marketplace identity and branding, aggregated catalog reads, single-merchant shop pages, unified multi-merchant checkout with automatic payment splitting, and commission previews |
| `disputes`        | `client.disputes`        | Yes (all but the reason list)     | Marketplace disputes — a shopper opens, lists, tracks, messages, and cancels a dispute on their own order; the operator resolves it in the admin                                                                 |
| `system`          | `client.system`          | No                                | Health checks and store metadata                                                                                                                                                                                 |

<Note>
  **Building a marketplace?** When a deployment runs as a marketplace, you authenticate the storefront with a **marketplace operator key**. The catalog services (`products`, `taxonomy`, `search`) then return data aggregated across **every active merchant** — pass `storeId` to narrow them to a single merchant's shop page. Use `client.marketplace.getMarketplaceInfo` for the marketplace's identity and branding (or one merchant's full store information), and `client.marketplace` to check out a single cart spanning multiple merchants with one payment that is split to each merchant automatically. See the [Marketplace](/sdk/api-reference/classes/MarketplaceService) reference.
</Note>

<Note>
  **Currency.** Each store sets its own currency, returned as `store.default_currency` (with the accepted list in `store.currencies`) from `client.system.getStoreInfo`. Catalog prices are expressed in that currency, so there's no separate currency endpoint to call. See the [Currency](/currency) guide for single- and multi-currency storefronts.
</Note>

## Next Steps

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

<CardGroup cols={2}>
  <Card title="Products" icon="box" href="/sdk/api-reference/classes/ProductsService">
    Manage your product catalog, categories, and inventory.
  </Card>

  <Card title="Orders" icon="cart-shopping" href="/sdk/api-reference/classes/OrdersService">
    Handle the full lifecycle of commerce orders.
  </Card>

  <Card title="Customers" icon="users" href="/sdk/api-reference/classes/CustomersService">
    Manage customer profiles and analytics.
  </Card>

  <Card title="Authentication" icon="lock" href="/sdk/api-reference/classes/AuthenticationService">
    Secure customer sessions and authentication flows.
  </Card>

  <Card title="Cart & Wishlist" icon="bag-shopping" href="/sdk/api-reference/classes/CartWishlistService">
    Persistent cart and wishlist tied to customer sessions.
  </Card>

  <Card title="System & Store" icon="gauge" href="/sdk/api-reference/classes/SystemService">
    Monitor health status and retrieve comprehensive store metadata.
  </Card>

  <Card title="Marketplace" icon="store" href="/sdk/api-reference/classes/MarketplaceService">
    Aggregate many merchants, run a unified multi-merchant checkout, and split payments automatically.
  </Card>
</CardGroup>
