> ## Documentation Index
> Fetch the complete documentation index at: https://strapi-suite.littlebox.pt/llms.txt
> Use this file to discover all available pages before exploring further.

# Cart

> Read, quote and update the cart.

The cart lives on the server: in the guest session, or on the account when the customer is logged in. You read it with `GET /cart` and you write it with `POST /cart/quote`, which saves the cart first and then prices it.

> [!WARNING]
>
> `POST /cart/quote` **replaces the whole stored cart** with the body you send. Always send the full cart: lines,
> promotion codes, gift choices, email, destination and shipping method. A field you leave out is cleared. The safe
> pattern is: read the cart, change it, send it back.

Session: guest or login, following the [mode](https://strapi-suite.littlebox.pt/frontend/guides/ecommerce/overview.md#customer-accounts-modes). Rate limit: `cart.quote`.

## Get the Cart

`GET /cart`

Returns the stored cart, not priced. A new session returns the empty cart.

```json Response 200 theme={null}
{
  "lines": [{ "variantId": 31, "quantity": 2 }],
  "promotionCodes": ["WELCOME10"],
  "giftChoices": {},
  "email": null,
  "destination": { "country": "PT", "postalCode": "1000-001" },
  "shippingMethod": { "providerId": "manual", "serviceId": "3" },
  "locale": "en"
}
```

## Quote the Cart

`POST /cart/quote`

| Field | Type | Description |
| - | - | - |
| `lines` | array, required | 0 to 100 lines of `{ variantId, quantity }`. Both are integers; `quantity` is 1 to 1000. An empty list returns an empty quote. |
| `locale` | string | A Strapi locale. Default: the default locale. |
| `email` | string or null | The guest's email, up to 254 characters. Some promotions depend on it. A logged in customer always uses the account email, so the API ignores this field. |
| `promotionCodes` | string\[] | Up to 5 codes of up to 40 characters. Codes are trimmed, upper cased and deduplicated. |
| `giftChoices` | object | Up to 10 entries. See [Gifts](https://strapi-suite.littlebox.pt/frontend/guides/ecommerce/promotions.md#gifts-buy-x-get-y). |
| `destination` | object or null | `{ country, postalCode? }`. `country` is an ISO code such as `PT` (2 upper case letters); `postalCode` is up to 20 characters. |
| `shippingMethod` | object or null | `{ providerId, serviceId }` taken from `shippingOptions`. |

Unknown fields are ignored.

```json Request theme={null}
{
  "lines": [{ "variantId": 31, "quantity": 2 }],
  "locale": "en",
  "email": null,
  "promotionCodes": ["WELCOME10"],
  "giftChoices": {},
  "destination": { "country": "PT", "postalCode": "1000-001" },
  "shippingMethod": { "providerId": "manual", "serviceId": "3" }
}
```

```json Response 200 theme={null}
{
  "lines": [
    {
      "variantId": 31,
      "productId": 12,
      "sku": "LSS-TEE-BLK-M",
      "name": "Littlebox Strapi Suite T-Shirt",
      "option": "Black / M",
      "imageUrl": "/uploads/t_shirt_black_9f1c2a.jpg",
      "unitPrice": 2500,
      "unitDiscount": 0,
      "quantity": 2,
      "total": 5000,
      "tax": 23,
      "isGift": false,
      "promotionIds": [5]
    }
  ],
  "promotions": [
    { "promotionId": 5, "name": "Welcome offer", "code": "WELCOME10", "amount": 500, "classes": ["ORDER_DISCOUNT"] }
  ],
  "codes": [{ "code": "WELCOME10", "status": "APPLIED", "message": "Code applied." }],
  "giftOptions": [],
  "unavailableGifts": [],
  "totals": {
    "itemsOriginal": 5000,
    "productDiscount": 0,
    "subtotal": 5000,
    "orderDiscount": 500,
    "shippingOriginal": 490,
    "shippingDiscount": 0,
    "shippingTotal": 490,
    "total": 4990,
    "totalDiscount": 500
  },
  "taxes": [{ "rate": 23, "base": 4057, "vat": 933, "gross": 4990 }],
  "currency": "EUR",
  "shippingOptions": [
    { "providerId": "manual", "serviceId": "3", "name": "Standard delivery", "price": 490, "estimatedDays": null },
    { "providerId": "dpd-portugal", "serviceId": "PICKUP", "name": "DPD Pickup", "price": 390, "estimatedDays": 2, "requiresPickupPoint": true }
  ],
  "selectedShipping": { "providerId": "manual", "serviceId": "3", "name": "Standard delivery", "price": 490, "estimatedDays": null }
}
```

How to read the quote:

| Field | Meaning |
| - | - |
| `lines[].unitDiscount` | Product discount per unit. `total` is `(unitPrice - unitDiscount) × quantity`. |
| `lines[].isGift` | A gift added by a promotion. Show it without quantity or remove controls. |
| `promotions` | Every promotion that applies, with its public name in the quote's locale, its code (`null` for an automatic promotion) and the amount it saves. |
| `codes` | One entry per code you sent, with a public status and a message in English or Portuguese. Translate the status yourself if you need other languages. |
| `totals.subtotal` | `itemsOriginal - productDiscount`. |
| `totals.shippingOriginal`, `shippingTotal` | `null` until a shipping method is selected. |
| `totals.total` | What the customer pays, before store credit. Send this value as `expectedTotal` when you place the order. |
| `shippingOptions` | `null` without a `destination`. `[]` when the store does not ship there. Otherwise the options sorted by price. |
| `selectedShipping` | The chosen option, priced for this cart, or `null`. |

Errors: `400` with a field code (`required`, `invalid`, `too_many`, `too_long`, `invalid_country`, `invalid_email`, `invalid_locale`); `400 VARIANT_UNAVAILABLE` on `lines.<i>.variantId` (unknown or inactive variant); `400 INSUFFICIENT_STOCK` on `lines.<i>.quantity`; `400 SHIPPING_UNAVAILABLE` on `shipping` (the method does not serve the destination or cannot take the cart); `401 SESSION_INVALID`, `LOGIN_REQUIRED`, `CUSTOMER_SESSION_INVALID`; `429 RATE_LIMITED`.

> [!NOTE]
>
> Strapi saves the cart **before** it prices it. When a quote fails with `VARIANT_UNAVAILABLE` or
> `INSUFFICIENT_STOCK`, the cart is already stored. Read it back with `GET /cart`, point the customer at the line in
> `errors[].path`, and let them lower the quantity or remove the line.

## Cart Server Actions

```ts src/lib/store/cart.ts theme={null}
import type { StoredCart } from "./types";

/** The full body of POST /cart/quote and POST /discounts/apply. */
export function cartBody(cart: StoredCart, locale: string) {
  return {
    lines: cart.lines,
    locale,
    email: cart.email,
    promotionCodes: cart.promotionCodes,
    giftChoices: cart.giftChoices,
    destination: cart.destination,
    shippingMethod: cart.shippingMethod,
  };
}
```

```ts src/app/(store)/cart/actions.ts theme={null}
"use server";

import { revalidatePath } from "next/cache";
import { getLocale } from "next-intl/server";
import { storeFetch } from "@/lib/store/client";
import { withSession } from "@/lib/store/session";
import { cartBody } from "@/lib/store/cart";
import { toActionError, type ActionResult } from "@/lib/store/result";
import type { GiftChoice, Quote, StoredCart } from "@/lib/store/types";

async function updateCart(change: (cart: StoredCart) => StoredCart): Promise<ActionResult<Quote>> {
  const locale = await getLocale();
  try {
    const quote = await withSession("checkout", async (auth) => {
      const cart = await storeFetch<StoredCart>("/cart", { auth });
      return storeFetch<Quote>("/cart/quote", { method: "POST", auth, body: cartBody(change(cart), locale) });
    });
    revalidatePath("/cart");
    return { ok: true, data: quote };
  } catch (error) {
    revalidatePath("/cart");
    return toActionError(error);
  }
}

export async function addToCart(variantId: number, quantity = 1) {
  return updateCart((cart) => {
    const line = cart.lines.find((l) => l.variantId === variantId);
    const lines = line
      ? cart.lines.map((l) => (l.variantId === variantId ? { ...l, quantity: Math.min(l.quantity + quantity, 1000) } : l))
      : [...cart.lines, { variantId, quantity }];
    return { ...cart, lines };
  });
}

export async function setQuantity(variantId: number, quantity: number) {
  return updateCart((cart) => ({
    ...cart,
    lines:
      quantity <= 0
        ? cart.lines.filter((l) => l.variantId !== variantId)
        : cart.lines.map((l) => (l.variantId === variantId ? { ...l, quantity } : l)),
  }));
}

export async function removeCode(code: string) {
  return updateCart((cart) => ({ ...cart, promotionCodes: cart.promotionCodes.filter((c) => c !== code) }));
}

export async function setDestination(country: string, postalCode?: string) {
  // A new destination can change the options: clear the method and ask the customer again.
  return updateCart((cart) => ({ ...cart, destination: { country, postalCode }, shippingMethod: null }));
}

export async function chooseShipping(providerId: string, serviceId: string) {
  return updateCart((cart) => ({ ...cart, shippingMethod: { providerId, serviceId } }));
}

export async function chooseGift(promotionId: number, choice: GiftChoice) {
  return updateCart((cart) => ({ ...cart, giftChoices: { ...cart.giftChoices, [promotionId]: choice } }));
}

export async function setCartEmail(email: string) {
  return updateCart((cart) => ({ ...cart, email }));
}
```

```tsx src/app/(store)/shop/products/[slug]/add-to-cart.tsx theme={null}
"use client";

import { useTransition, useState } from "react";
import { useRouter } from "next/navigation";
import { addToCart } from "@/app/(store)/cart/actions";

export default function AddToCart({ variantId, disabled }: { variantId: number; disabled: boolean }) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [message, setMessage] = useState<string | null>(null);
  return (
    <>
      <button
        disabled={disabled || pending}
        onClick={() =>
          startTransition(async () => {
            const result = await addToCart(variantId);
            if (result.ok) return setMessage("Added to your cart.");
            if (result.code === "LOGIN_REQUIRED") return router.push("/account/login");
            if (result.code === "INSUFFICIENT_STOCK") return setMessage("Not enough stock for this quantity.");
            setMessage("Something went wrong. Please try again.");
          })
        }
      >
        Add to cart
      </button>
      {message && <p>{message}</p>}
    </>
  );
}
```

The cart page reads the stored cart and prices it on every render. It never opens a session: a visitor without a cookie simply has an empty cart.

```tsx src/app/(store)/cart/page.tsx theme={null}
import { getLocale } from "next-intl/server";
import { storeFetch, StoreApiError } from "@/lib/store/client";
import { readAuth } from "@/lib/store/session";
import { cartBody } from "@/lib/store/cart";
import { formatMoney } from "@/lib/store/money";
import type { Quote, StoredCart } from "@/lib/store/types";

export default async function CartPage() {
  const auth = await readAuth();
  if (!auth.checkout && !auth.customer) return <p>Your cart is empty.</p>;
  const locale = await getLocale();
  let quote: Quote;
  try {
    const cart = await storeFetch<StoredCart>("/cart", { auth });
    quote = await storeFetch<Quote>("/cart/quote", { method: "POST", auth, body: cartBody(cart, locale) });
  } catch (error) {
    // A dead session renders as an empty cart; the next Server Action replaces the cookie.
    if (error instanceof StoreApiError && error.status === 401) return <p>Your cart is empty.</p>;
    throw error;
  }
  if (quote.lines.length === 0) return <p>Your cart is empty.</p>;
  return (
    <main>
      {quote.lines.map((line) => (
        <div key={`${line.variantId}-${line.isGift}`}>
          {line.name} {line.option} × {line.quantity} · {formatMoney(line.total, locale)}
          {line.isGift && " (gift)"}
        </div>
      ))}
      {quote.promotions.map((p) => (
        <div key={p.promotionId}>
          {p.name} · −{formatMoney(p.amount, locale)}
        </div>
      ))}
      <strong>Total {formatMoney(quote.totals.total, locale)}</strong>
    </main>
  );
}
```

> [!TIP]
>
> When a quote fails with a stock error, render the stored cart lines (from `GET /cart`) next to the messages from
> `errors[].path` instead of throwing, so the customer can fix the cart.


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