> ## Documentation Index
> Fetch the complete documentation index at: https://docs.komerza.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Basket

> Manage shopping cart items with the Komerza client library

## Overview

The basket (shopping cart) is stored in the browser's localStorage and persists across page reloads. All basket operations are synchronous and update the local state immediately.

<Note>
  The `komerza` object is available globally after including the script. Call
  `komerza.init('your-store-id')` before using any other methods.
</Note>

## Adding Items

Add a product variant to the basket with a specified quantity.

```javascript theme={null}
komerza.addToBasket(productId, variantId, quantity);
```

### Parameters

<ParamField path="productId" type="string" required>
  The unique identifier of the product
</ParamField>

<ParamField path="variantId" type="string" required>
  The unique identifier of the product variant
</ParamField>

<ParamField path="quantity" type="number">
  How many items to add (defaults to 1 if not provided)
</ParamField>

### Example

```javascript theme={null}
// Add 2 items of a specific product variant
komerza.addToBasket("prod_abc123", "var_xyz789", 2);

// Add to cart button handler
document.getElementById("add-to-cart").addEventListener("click", () => {
  const productId = "prod_abc123";
  const variantId = document.getElementById("variant-select").value;
  const quantity = parseInt(document.getElementById("quantity").value) || 1;

  komerza.addToBasket(productId, variantId, quantity);
  alert("Added to cart!");
});
```

## Viewing Basket

Get all items currently in the basket.

```javascript theme={null}
const items = komerza.getBasket();
```

### Returns

Returns an array of `BasketItem` objects:

```typescript theme={null}
interface BasketItem {
  productId: string; // Product identifier
  variantId: string; // Variant identifier
  quantity: number; // Number of items
}
```

### Example

```javascript theme={null}
// Display cart items
const basket = komerza.getBasket();

if (basket.length === 0) {
  console.log("Cart is empty");
} else {
  basket.forEach((item) => {
    console.log(
      `Product: ${item.productId}, Variant: ${item.variantId}, Qty: ${item.quantity}`
    );
  });
}
```

## Getting Item Count

Get the total number of items in the basket (sum of all quantities).

```javascript theme={null}
const count = komerza.getBasketItemCount();
```

### Returns

Returns a number representing the total quantity of all items.

### Example

```javascript theme={null}
// Update cart badge
function updateCartBadge() {
  const count = komerza.getBasketItemCount();
  document.getElementById("cart-count").textContent = count;

  if (count > 0) {
    document.getElementById("cart-badge").style.display = "block";
  }
}

// Call on page load and after cart changes
updateCartBadge();
```

## Removing Items

Remove a specific product variant from the basket entirely.

```javascript theme={null}
komerza.removeFromBasket(productId, variantId);
```

### Parameters

<ParamField path="productId" type="string" required>
  The product identifier to remove
</ParamField>

<ParamField path="variantId" type="string" required>
  The variant identifier to remove
</ParamField>

### Example

```javascript theme={null}
// Remove button handler
function removeItem(productId, variantId) {
  if (confirm("Remove this item from cart?")) {
    komerza.removeFromBasket(productId, variantId);
    updateCartDisplay();
  }
}
```

## Clearing Basket

Remove all items from the basket at once.

```javascript theme={null}
komerza.clearBasket();
```

### Example

```javascript theme={null}
// Clear cart button
document.getElementById("clear-cart").addEventListener("click", () => {
  if (confirm("Remove all items from cart?")) {
    komerza.clearBasket();
    updateCartDisplay();
  }
});
```

## Backup & Restore

Create backups of the basket state and restore them later. Useful for handling checkout errors or implementing "save for later" features.

### Create Backup

```javascript theme={null}
const success = komerza.createBasketBackup();
```

Returns `true` if backup was created successfully.

### Restore Backup

```javascript theme={null}
const success = komerza.restoreBasketFromBackup();
```

Returns `true` if backup was restored successfully.

### Example

```javascript theme={null}
// Save basket before checkout
async function proceedToCheckout() {
  // Create backup in case checkout fails
  komerza.createBasketBackup();

  try {
    const order = await komerza.checkout(email, couponCode);
    // Success - redirect to payment
    window.location.href = order.data.gatewayMetadata.clientSecret;
  } catch (error) {
    // Restore basket on error
    komerza.restoreBasketFromBackup();
    alert("Checkout failed. Your cart has been restored.");
  }
}
```

## Validation

Validate that the basket data is intact and properly formatted.

```javascript theme={null}
const isValid = komerza.validateBasketIntegrity();
```

Returns `true` if basket data is valid, `false` if corrupted.

### Example

```javascript theme={null}
// Validate on page load
window.addEventListener("load", () => {
  if (!komerza.validateBasketIntegrity()) {
    console.error("Cart data corrupted, clearing basket");
    komerza.clearBasket();
  }
});
```

## Advanced Operations

### Merge Baskets

Merge items from another basket into the current basket. Useful for syncing carts across devices or sessions.

```javascript theme={null}
const mergedBasket = komerza.mergeBaskets(otherBasket);
```

**Parameters:**

* `otherBasket` - Array of `BasketItem` objects to merge

**Returns:** The merged basket as an array of `BasketItem` objects.

```javascript theme={null}
// Example: Load saved cart from server and merge
async function syncCart() {
  const savedCart = await fetch("/api/saved-cart").then((r) => r.json());
  const merged = komerza.mergeBaskets(savedCart);
  console.log(`Merged ${merged.length} items`);
}
```

### Move Basket Item

Move a specific item from one product/variant to another.

```javascript theme={null}
const success = komerza.moveBasketItem(
  fromProductId,
  fromVariantId,
  toProductId,
  toVariantId
);
```

**Parameters:**

* `fromProductId` - Source product ID
* `fromVariantId` - Source variant ID
* `toProductId` - Destination product ID
* `toVariantId` - Destination variant ID

**Returns:** `true` if the item was moved successfully.

```javascript theme={null}
// Example: User switches variant selection
function changeVariant(productId, oldVariantId, newVariantId) {
  komerza.moveBasketItem(productId, oldVariantId, productId, newVariantId);
  updateCartDisplay();
}
```

### Get Basket Statistics

Get detailed statistics about the current basket.

```javascript theme={null}
const stats = komerza.getBasketStats();
```

**Returns:** An object containing basket statistics (structure varies).

```javascript theme={null}
// Example: Display cart summary
const stats = komerza.getBasketStats();
console.log("Cart stats:", stats);
```

## Complete Example

Here's a complete shopping cart implementation:

```html theme={null}
<!DOCTYPE html>
<html>
  <head>
    <title>Shopping Cart</title>
    <script src="https://cdn.komerza.com/komerza.min.js"></script>
  </head>
  <body>
    <div id="cart">
      <h2>Shopping Cart (<span id="cart-count">0</span>)</h2>
      <div id="cart-items"></div>
      <button onclick="clearCart()">Clear Cart</button>
      <button onclick="checkout()">Checkout</button>
    </div>

    <script>
      // Initialize
      komerza.init("your-store-id");

      // Add to cart
      function addToCart(productId, variantId, quantity) {
        komerza.addToBasket(productId, variantId, quantity);
        updateCartDisplay();
      }

      // Update cart display
      function updateCartDisplay() {
        const basket = komerza.getBasket();
        const count = komerza.getBasketItemCount();

        document.getElementById("cart-count").textContent = count;

        const container = document.getElementById("cart-items");
        if (basket.length === 0) {
          container.innerHTML = "<p>Your cart is empty</p>";
          return;
        }

        container.innerHTML = basket
          .map(
            (item) => `
        <div class="cart-item">
          <span>Product: ${item.productId}</span>
          <span>Qty: ${item.quantity}</span>
          <button onclick="removeItem('${item.productId}', '${item.variantId}')">
            Remove
          </button>
        </div>
      `
          )
          .join("");
      }

      // Remove item
      function removeItem(productId, variantId) {
        komerza.removeFromBasket(productId, variantId);
        updateCartDisplay();
      }

      // Clear cart
      function clearCart() {
        if (confirm("Clear all items?")) {
          komerza.clearBasket();
          updateCartDisplay();
        }
      }

      // Checkout
      async function checkout() {
        const email = prompt("Enter your email:");
        if (!email) return;

        komerza.createBasketBackup();

        try {
          const order = await komerza.checkout(email, "");
          window.location.href = order.data.gatewayMetadata.clientSecret;
        } catch (error) {
          komerza.restoreBasketFromBackup();
          alert("Checkout failed: " + error.message);
        }
      }

      // Initialize display
      updateCartDisplay();
    </script>
  </body>
</html>
```

<Warning>
  Basket data is stored in localStorage - it's not synced across devices or
  browsers
</Warning>

## Next Steps

<CardGroup cols={2}>
  <Card title="Products" icon="box" href="/storefront/products">
    Learn how to fetch and display products
  </Card>

  <Card title="Checkout" icon="credit-card" href="/storefront/checkout">
    Process orders and handle payments
  </Card>
</CardGroup>
