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 CartWishlistService class (accessed via client.cartWishlist) manages shopping carts for both authenticated and anonymous users, along with customer wishlists.

Overview

The cart and wishlist APIs support full variant tracking and a unified media gallery system. This enables customers to save specific product selections (color, size, etc.) with accurate pricing, real-time stock levels, and variant-specific images.

Security Model

Cart and wishlist endpoints accept publishable keys (storefronts run in browsers), so a leaked publishable key alone is not enough to access another customer’s cart. When the request claims a customer_id (query or body), the gateway requires an xAuthToken header — the customer’s session JWT from client.authentication.login or verifyOtp. The resolved customer must match the claimed customer_id, otherwise the gateway returns 403 forbidden. Anonymous (session-only) carts skip this check and rely on the secrecy of X-Session-Id.
All wishlist endpoints (and mergeCart) always require xAuthToken because they are inherently customer-scoped. Only cart reads/writes that omit customer_id and rely solely on xSessionId may proceed unauthenticated.

Cart Management

getCart

Retrieve the current contents of a cart. This method supports both logged-in customers and anonymous guest sessions.
// Anonymous (no auth token needed)
const guestCart = await client.cartWishlist.getCart({
  xSessionId: 'guest-uuid-123'
});

// Authenticated (token required — JWT must resolve to customerId)
const cart = await client.cartWishlist.getCart({
  xAuthToken: customerSession.access_token,
  customerId: 'customer-uuid'
});

const firstItem = cart.items[0];
console.log(`Item: ${firstItem.product_name} (${firstItem.variant_name})`);
console.log(`Thumbnail: ${firstItem.thumbnail_url}`);

addToCart

Add a specific product variant to the cart. If the same variant already exists, its quantity will be incremented.
variant_id is required to specify the exact product selection. For products without variants, use the default variant ID.
// Anonymous Cart (no auth token needed)
await client.cartWishlist.addToCart({
  xSessionId: 'guest-uuid-123',
  requestBody: {
    variant_id: 'variant-uuid',
    quantity: 1
  }
});

// Authenticated Cart (token required)
await client.cartWishlist.addToCart({
  xAuthToken: customerSession.access_token,
  requestBody: {
    variant_id: 'variant-uuid',
    quantity: 1,
    customer_id: 'customer-uuid'
  }
});

updateCartItem

Update variables for a specific item already in the cart, such as changing the quantity.
// Anonymous (no auth token needed)
await client.cartWishlist.updateCartItem({
  id: 'cart-item-uuid',
  xSessionId: 'guest-uuid-123',
  requestBody: {
    quantity: 5
  }
});

// Authenticated (token required)
await client.cartWishlist.updateCartItem({
  id: 'cart-item-uuid', // The UUID of the item in the cart
  xAuthToken: customerSession.access_token,
  requestBody: {
    quantity: 5,
    customer_id: 'customer-uuid'
  }
});

clearCart

Remove all items from the cart in a single operation.
// Anonymous (no auth token needed)
await client.cartWishlist.clearCart({
  xSessionId: 'guest-uuid-123'
});

// Authenticated (token required)
await client.cartWishlist.clearCart({
  xAuthToken: customerSession.access_token,
  customerId: 'customer-uuid'
});

removeCartItem

Remove a specific item from the cart.
// Anonymous (no auth token needed)
await client.cartWishlist.removeCartItem({
  id: 'cart-item-uuid',
  xSessionId: 'guest-uuid-123'
});

// Authenticated (token required)
await client.cartWishlist.removeCartItem({
  id: 'cart-item-uuid',
  xAuthToken: customerSession.access_token,
  customerId: 'customer-uuid'
});

mergeCart

Combine an anonymous guest cart with a customer’s permanent cart. Carts are matched by both product_id and variant_id to prevent merging different variants of the same product.
mergeCart always requires xAuthToken — it links a guest session to a customer record, so the gateway must verify the caller actually owns that customer.
await client.cartWishlist.mergeCart({
  xAuthToken: customerSession.access_token,
  requestBody: {
    session_id: 'guest-session-uuid',
    customer_id: 'authenticated-customer-uuid'
  }
});

Wishlist Management

All wishlist endpoints require xAuthToken. Wishlists are inherently customer-scoped — there is no anonymous mode. The JWT must resolve to the same customer referenced by customer_id.

getWishlist

Retrieve a customer’s saved items, including variant and media details.
const { items } = await client.cartWishlist.getWishlist({
  xAuthToken: customerSession.access_token,
  customerId: 'customer-uuid'
});

addToWishlist

Save a specific product variant for later. Wishlists require an authenticated customer_id.
await client.cartWishlist.addToWishlist({
  xAuthToken: customerSession.access_token,
  requestBody: {
    variant_id: 'variant-uuid',
    customer_id: 'customer-uuid'
  }
});

removeFromWishlist

Remove an item from the customer’s wishlist.
await client.cartWishlist.removeFromWishlist({
  id: 'wishlist-item-uuid',
  xAuthToken: customerSession.access_token,
  customerId: 'customer-uuid'
});

moveWishlistToCart

An atomic operation that removes an item from the wishlist and adds it to the active cart. This operation preserves the variant_id and performs stock validation.
await client.cartWishlist.moveWishlistToCart({
  xAuthToken: customerSession.access_token,
  requestBody: {
    wishlist_item_id: 'wishlist-item-uuid',
    customer_id: 'customer-uuid',
    quantity: 1
  }
});

Response Objects

CartItem & WishlistItem

Both cart and wishlist items include structured data for optimized frontend rendering.
FieldTypeDescription
iduuidItem UUID in the cart or wishlist.
product_iduuidThe parent product identifier.
variant_iduuidThe specific identifier for the selected variation.
product_namestringName of the product.
variant_namestringDisplay name for the variant (e.g., “Space Gray”).
variant_attributesobjectJSON attributes like color or size.
product_skustringSKU for the specific variant.
thumbnail_urlstringPrimary image URL, prioritizing variant media.
mediaarrayFull gallery of variant-aware images and videos.
quantitynumber(Cart only) Number of items added.
unit_pricenumber(Cart only) Base price per unit.
selling_pricenumber(Cart only) Actual price including active sales.
total_pricenumber(Cart only) unit_price × quantity.
product_pricenumber(Wishlist only) Current price of the variant.
stock_availablenumberReal-time stock count for the variant.
has_variantsbooleanWhether the product supports variation selection.
created_atstringTimestamp of when the item was added.
{
    "id": "d1de278b-d260-42da-ae4a-8bb5d34477c3",
    "product_id": "b016b91e-8403-44be-80ca-77a2d55e7b2d",
    "variant_id": "6be67ee4-6657-4998-b728-3e99c075c01b",
    "product_name": "Samsung Galaxy S21",
    "variant_name": "Default",
    "variant_attributes": {},
    "product_sku": "SMG-S21-BLK",
    "thumbnail_url": "https://pub-41977a1f3228456da0137b210f2ece66.r2.dev/stores/.../primary-1774785162626.jpg",
    "media": [
        {
            "id": "cb00d540-692d-432e-9661-7757ac998f75",
            "url": "https://pub-41977a1f3228456da0137b210f2ece66.r2.dev/stores/.../primary-1774785162626.jpg",
            "type": "image",
            "alt_text": "Samsung Galaxy S21",
            "position": 0,
            "is_primary": true
        }
    ],
    "quantity": 2,
    "unit_price": 99999,
    "selling_price": 99999,
    "total_price": 199998,
    "stock_available": 49,
    "has_variants": false,
    "created_at": "2026-04-11T10:54:23Z",
    "updated_at": "2026-04-11T10:54:23Z"
}

Core Logic

Stock Validation

Stock checks are enforced against the specific variant during all cart operations. If the requested quantity exceeds stock_available, the API returns an insufficient_stock error code along with the current available count.

Pricing Logic

Prices are calculated at the variant level using the selling_price field. This ensures that different variations (e.g., larger sizes or premium colors) are priced accurately and that active promotions are automatically applied.

Frontend Patterns

Variant Selection & Add to Cart

When a user selects a variant and adds it to their cart, branch on whether you have a stored customer session:
// Read the stored session — set by client.authentication.login / verifyOtp
const customerSession = JSON.parse(localStorage.getItem('tybrite_session') ?? 'null');

const handleAddToCart = async (selectedVariant: Variant, quantity: number) => {
  try {
    if (customerSession?.access_token) {
      // Authenticated path — JWT must resolve to customer_id
      await client.cartWishlist.addToCart({
        xAuthToken: customerSession.access_token,
        requestBody: {
          variant_id: selectedVariant.variant_id,
          quantity,
          customer_id: customerSession.customer_id
        }
      });
    } else {
      // Anonymous path — session-only cart
      await client.cartWishlist.addToCart({
        xSessionId: sessionId,
        requestBody: {
          variant_id: selectedVariant.variant_id,
          quantity
        }
      });
    }
  } catch (error) {
    if (error.code === 'insufficient_stock') {
      alert(`Only ${error.available_stock} items available`);
    }
  }
};
Pro Tip: Use xSessionId for guest users. Tybrite will persist this guest cart until it is either merged via mergeCart (which requires xAuthToken) or cleared.
When a guest logs in, call mergeCart with the freshly minted xAuthToken to fold their guest cart into their customer cart before clearing X-Session-Id.

Response Codes

CodeMeaning
200Success on reads, updates, clearCart, and mergeCart.
201Success on addToWishlist — a new wishlist item was created.
400insufficient_stock, missing required fields, or invalid body.
401Missing or invalid xAuthToken.
403The customer token does not match the customer_id in the request.
404Variant, wishlist item, or cart item not found.
409Item already in wishlist (on addToWishlist).