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

## Step 2: Add Items to Cart

Add products to the cart using a variant ID. You can get variant IDs from the [product endpoints](/storefront/products).

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

// Add a product to the cart
await addToCart(cart.id, "var_xyz789", 2);
```

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

### 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](/shop-apis/cart-checkout-endpoint).

## 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(variantId, quantity = 1) {
  const id = await ensureCart();
  const res = await fetch(
    `${API_BASE}/carts/${id}/items?storefront_token=${STOREFRONT_TOKEN}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ variantId, quantity })
    }
  );
  return res.json();
}

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

<CardGroup cols={2}>
  <Card title="Style Your Checkout" icon="palette" href="/storefront/checkout">
    Make your checkout page match your brand
  </Card>

  <Card title="Cart API Reference" icon="code" href="/api-reference/storefront/carts/create-cart">
    See all cart operations
  </Card>
</CardGroup>
