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

# Building a Cart & Checkout

> End-to-end guide for implementing shopping cart and checkout

This guide walks through the complete flow from adding items to a cart through redirecting to checkout.

## Overview

```mermaid theme={null}
flowchart LR
    A[Create Cart] --> B[Add Items]
    B --> C[Redirect to Checkout]
    C --> D[Customer Completes Purchase]
```

## Step 1: Create a Cart

First, create an empty cart. You'll get back a `cart_id` that you'll use for all subsequent operations.

```javascript theme={null}
const STOREFRONT_TOKEN = "your_storefront_token";
const API_BASE = "https://storefront-api.fourthwall.com/v1";

async function createCart() {
  const res = await fetch(`${API_BASE}/carts?storefront_token=${STOREFRONT_TOKEN}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ currency: "USD" })
  });
  return res.json();
}

const cart = await createCart();
console.log(cart.id); // e.g., "22222222-2222-2222-2222-222222222222"
```

> [!TIP]
>
> Store the `cart_id` in localStorage or a cookie so it persists across page refreshes.

## Step 2: Add Items to Cart

Add products to the cart using a variant ID. You can get variant IDs from the [product endpoints](https://docs.fourthwall.com/storefront/products.md).

```javascript theme={null}
async function addToCart(cartId, items) {
  const res = await fetch(
    `${API_BASE}/carts/${cartId}/add?storefront_token=${STOREFRONT_TOKEN}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ items })
    }
  );
  return res.json();
}

// Add a product to the cart
await addToCart(cart.id, [{ variantId: "55555555-5555-5555-5555-555555555555", quantity: 2 }]);
```

### Adding a bundle

A [bundle](https://docs.fourthwall.com/storefront/products.md#bundles) (`type: BUNDLE`) has no variants of its own. To add it, pick **one variant of every product** in its `offers` and send them in a single request, all with the same `quantity` and with `bundleId` set to the bundle's `id`:

```javascript theme={null}
function bundleItems(bundle, selectedVariantIds, quantity = 1) {
  return bundle.offers.map((offer) => ({
    variantId: selectedVariantIds[offer.id] ?? offer.variants[0].id,
    quantity,
    bundleId: bundle.id
  }));
}

// bundle = result of GET /v1/products/{slug} with type === "BUNDLE"
await addToCart(cart.id, bundleItems(bundle, { [hatOfferId]: chosenHatVariantId }));
```

The items are validated together: a missing product, a variant that does not belong to the bundle, or different quantities return `400 CART_INCOMPLETE_BUNDLE_ERROR`. In the cart response the bundle's items carry `groupedBy: { "type": "BUNDLE", "bundleId", "groupedId" }` - items with the same `groupedId` form one bundle instance, so you can render them as a group and price them with the bundle's `price`.

> [!NOTE]
>
> The same `items` shape (including `bundleId`) is accepted when creating the cart in Step 1, so a bundle can be the first thing in a new cart.

## Step 3: View Cart Contents

Fetch the current cart to display items to the user:

```javascript theme={null}
async function getCart(cartId) {
  const res = await fetch(
    `${API_BASE}/carts/${cartId}?storefront_token=${STOREFRONT_TOKEN}`
  );
  return res.json();
}

const currentCart = await getCart(cart.id);
console.log(currentCart.items); // Array of cart items
console.log(currentCart.totals); // Price totals
```

## Step 4: Redirect to Checkout

When the customer is ready to purchase, redirect them to the Fourthwall checkout page using the cart ID:

```javascript theme={null}
function redirectToCheckout(cartId, currency = "USD") {
  const checkoutDomain = "your-shop.fourthwall.com"; // Your checkout domain
  const params = new URLSearchParams({ cartCurrency: currency, cartId });
  const checkoutUrl = `https://${checkoutDomain}/checkout/?${params.toString()}`;

  window.location.href = checkoutUrl;
}

// When user clicks "Checkout" button
redirectToCheckout(cart.id, "USD");
```

> [!WARNING]
>
> The checkout URL format is:
>
> ```
> https://{checkout_domain}/checkout/?cartCurrency={currency}&cartId={cart_id}
> ```
>
> Make sure to use your shop's checkout domain, not `storefront-api.fourthwall.com`.

### Alternative: Domain cart checkout URL

You can also use the domain cart-checkout entrypoint:

```text theme={null}
https://{shop_domain}/cart/checkout?cartId={cart_id}&currency={currency}
```

### Alternative: Direct product checkout URL

If you want to skip cart creation and redirect from variant IDs directly, use:

```text theme={null}
https://{shop_domain}/cart/checkout?products={variant_id}:1
```

For multiple variants:

```text theme={null}
https://{shop_domain}/cart/checkout?products={variant_id_1}:1,{variant_id_2}:2
```

`quantity` is optional and defaults to `1`.

For full behavior details, see [Cart Checkout Endpoint](https://docs.fourthwall.com/shop-apis/cart-checkout-endpoint.md).

## Complete Example

Here's a complete implementation you can adapt:

```javascript theme={null}
const STOREFRONT_TOKEN = "your_storefront_token";
const API_BASE = "https://storefront-api.fourthwall.com/v1";
const CHECKOUT_DOMAIN = "your-shop.fourthwall.com";

// Cart state
let cartId = localStorage.getItem("cartId");

async function ensureCart() {
  if (cartId) {
    // Verify cart still exists
    const res = await fetch(
      `${API_BASE}/carts/${cartId}?storefront_token=${STOREFRONT_TOKEN}`
    );
    if (res.ok) return cartId;
  }

  // Create new cart
  const res = await fetch(`${API_BASE}/carts?storefront_token=${STOREFRONT_TOKEN}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ currency: "USD" })
  });
  const cart = await res.json();
  cartId = cart.id;
  localStorage.setItem("cartId", cartId);
  return cartId;
}

async function addToCart(items) {
  const id = await ensureCart();
  const res = await fetch(
    `${API_BASE}/carts/${id}/add?storefront_token=${STOREFRONT_TOKEN}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ items })
    }
  );
  return res.json();
}

// A regular product
await addToCart([{ variantId, quantity: 1 }]);

// A bundle: one variant per product in bundle.offers, same bundleId
await addToCart(bundle.offers.map((offer) => ({ variantId: offer.variants[0].id, quantity: 1, bundleId: bundle.id })));

function checkout() {
  if (!cartId) {
    alert("Your cart is empty");
    return;
  }
  const params = new URLSearchParams({ cartCurrency: "USD", cartId });
  window.location.href = `https://${CHECKOUT_DOMAIN}/checkout/?${params.toString()}`;
}
```

## Next Steps

> [card] [Style Your Checkout](https://docs.fourthwall.com/storefront/checkout.md)
>
> Make your checkout page match your brand

> [card] [Cart API Reference](https://docs.fourthwall.com/api-reference/storefront/carts/create-cart.md)
>
> See all cart operations


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.