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.
The komerza object is available globally after including the script. Call
komerza.init('your-store-id') before using any other methods.
Adding Items
Add a product variant to the basket with a specified quantity.
komerza.addToBasket(productId, variantId, quantity);
Parameters
The unique identifier of the product
The unique identifier of the product variant
How many items to add (defaults to 1 if not provided)
Example
// 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.
const items = komerza.getBasket();
Returns
Returns an array of BasketItem objects:
interface BasketItem {
productId: string; // Product identifier
variantId: string; // Variant identifier
quantity: number; // Number of items
}
Example
// 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).
const count = komerza.getBasketItemCount();
Returns
Returns a number representing the total quantity of all items.
Example
// 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.
komerza.removeFromBasket(productId, variantId);
Parameters
The product identifier to remove
The variant identifier to remove
Example
// 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.
Example
// 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
const success = komerza.createBasketBackup();
Returns true if backup was created successfully.
Restore Backup
const success = komerza.restoreBasketFromBackup();
Returns true if backup was restored successfully.
Example
// 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.
const isValid = komerza.validateBasketIntegrity();
Returns true if basket data is valid, false if corrupted.
Example
// 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.
const mergedBasket = komerza.mergeBaskets(otherBasket);
Parameters:
otherBasket - Array of BasketItem objects to merge
Returns: The merged basket as an array of BasketItem objects.
// 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.
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.
// 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.
const stats = komerza.getBasketStats();
Returns: An object containing basket statistics (structure varies).
// Example: Display cart summary
const stats = komerza.getBasketStats();
console.log("Cart stats:", stats);
Complete Example
Here’s a complete shopping cart implementation:
<!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>
Basket data is stored in localStorage - it’s not synced across devices or
browsers
Next Steps