# Carts

Add goods, change quantities and keep the buyer's place across reloads and devices.

These examples use `@orbcart/client`. It works in the browser, on your server and
in an agent. [React](/docs/shop/react-checkout) builds on it.

## Connect once

```ts title="lib/commerce.ts"
import { createCommerce } from "@orbcart/client";

export const commerce = createCommerce({
  url: process.env.ORBCART_URL,
  key: process.env.ORBCART_PUBLISHABLE_KEY,
});
```

Pass `language: "en"` with the language of the page the buyer reads, and the text you wrote
per language, such as a [shipping method's title](/docs/shop/shipping#in-several-languages),
comes back in it. Prices and what is offered do not depend on it.

Use the **OrbCart** publishable key (`pk_test_…`) from [`orbcart dev`](/docs/cart/cli),
not a Stripe key. It is safe in the browser. For a deployed storefront, add its
origin to the Channel's [`origins`](/docs/shop/configuration#origins-and-returnurl).

## Create a Cart and add a Line

```ts
const cart = await commerce.cart();
const current = await cart.add("BACKPACK-30-GREEN", { quantity: 2 });
```

`cart` is a handle you call methods on. `current` is the server's answer: the
whole Cart, with Lines, prices and what is still missing. **Every change answers
with the whole Cart**, so you never need a second request to refresh.

The browser sends only a reference and a quantity. Prices always come from your
`offers` function.

A buyer's first add can create the Cart and fill it in one request, so it is as
quick as every add after it:

```ts
const cart = await commerce.cart({ lines: [{ reference: "BACKPACK-30-GREEN", quantity: 2 }] });
```

The Lines go in as `cart.add` would add them one after another. Retried with the
same creation key, the request adds them once.

## Read the Cart

```ts
current.lines; // [{ id, reference, quantity, status, offer: { title, price } }]
current.estimate.totals; // { subtotal, discount, shipping, tax, total }
current.missing; // ["ship_to", "email"]
current.changes; // [{ type: "price_changed", line, from, to }]
current.shippingMethods; // [{ id: "standard", title, price, deliveryTime }]
current.paymentMethods; // [{ id: "card", provider: "stripe", flow: "inline" }]
current.lifecycle; // { status: "open" }
```

Show `changes` to the buyer. They explain why something differs from what the
buyer expected, such as a price that went up or a Line that sold out.

## Change and remove Lines

Use the Line's `id` from `current.lines`, not the reference:

```ts
const [line] = current.lines;

await cart.setQuantity(line.id, 3);
await cart.remove(line.id);
```

Adding the same reference again increases that Line's quantity.

## Set contact, address and shipping

```ts
await cart.setContact({ email: "anna@example.com" });
await cart.setShipTo({
  name: "Anna Berg",
  line1: "Bergstraße 12",
  postalCode: "10115",
  city: "Berlin",
  country: "DE",
});
await cart.setShipping("express");
```

Without a separate billing address, the delivery address bills. Use
`cart.setBillTo(address)` and `cart.removeBillTo()` to change that.

You can also pass everything at once to [`cart.quote()`](/docs/shop/quotes).

Each country asks for different address fields. Ask once per country:

```ts
const format = await commerce.addressFormat("IE");
// { postalCode: { required, pattern, kind: "eircode" }, region: { required, kind: "county", options } }
```

## Keep the Cart across reloads

Save the token in your session. Open the Cart again with it:

```ts
const cart = commerce.openCart(savedToken);
const current = await cart.read();
```

`openCart()` makes a handle without a request. `read()` fetches the state.

<Callout type="warn" title="Treat the token like a password">
A Cart token opens that Cart and its personal data. Never put it in a URL, an analytics event or a
log. A server-rendered storefront keeps it in an HttpOnly, Secure, SameSite cookie. Nordgrat keeps
it for 180 days, the Cart's inactivity period.
</Callout>

### In a cookie

In React Router, one cookie holds the token for your server, and one route lets the page save a new
one:

```ts title="app/cart-cookie.server.ts"
import { createCookie } from "react-router";

// Path `/` and SameSite Lax are React Router's defaults. 180 days: as long as OrbCart keeps an idle Cart.
export const cartCookie = createCookie("cart", {
  httpOnly: true,
  secure: true,
  maxAge: 15_552_000,
});
```

```ts title="app/routes/cart-token.ts"
import type { ActionFunctionArgs } from "react-router";
import { cartCookie } from "../cart-cookie.server";

export async function action({ request }: ActionFunctionArgs) {
  // Only your own pages may set the token, or another site could slip the buyer a Cart it reads.
  if (request.headers.get("Origin") !== new URL(request.url).origin) {
    return new Response(null, { status: 403 });
  }
  const token = (await request.formData()).get("token");
  if (typeof token !== "string") return new Response(null, { status: 400 });

  return new Response(null, {
    status: 204,
    headers: { "Set-Cookie": await cartCookie.serialize(token), "Cache-Control": "no-store" },
  });
}
```

Register it in `app/routes.ts` as `route("cart-token", "routes/cart-token.ts")`. A loader reads the
token with `cartCookie.parse(request.headers.get("Cookie"))`; the page saves a new one with
`fetch("/cart-token", { method: "POST", body: new URLSearchParams({ token }) })`.
[Add to cart and a mini cart](/docs/shop/add-to-cart) puts both to work.

## After the purchase

Once the buyer has handed the purchase over, their bag should be empty again.
Move to the next Cart:

```ts
import { isSubmitted } from "@orbcart/client";

if (isSubmitted(current)) {
  const next = await commerce.continueShopping(cart.token);
  saveCartToken(next.token);
}
```

`isSubmitted` is true when the Cart is ordered, or its payment only waits for the
provider's answer. While the buyer still has a step to do, such as 3-D Secure, it
is the same purchase.

Every call within 24 hours returns the **same** next Cart, so two open tabs keep
shopping together.

## One shopping Cart for the whole storefront

`createShoppingCart()` does all of the above for any framework. It keeps the
buyer's current Cart, creates the first one with the first line in one request, and moves on
by itself: to the next Cart after a purchase, to the buyer's own after a
sign-in on another device, and to a fresh one when OrbCart no longer knows the
Cart. The buyer never sees an error for any of it.

```ts
import { createShoppingCart } from "@orbcart/client";

const shopping = createShoppingCart({
  commerce,
  token: savedToken,
  onCartChange: (cart) => saveCartToken(cart.token),
});

shopping.subscribe((cart) => render(cart));
await shopping.follow(savedToken); // once the page has loaded
await shopping.add("TENT-1");
```

`cart` is the Cart to show, `follow(token)` takes the token you saved now, and
`shopOn()` moves on after a receipt was shown. In React,
[`CartProvider`](/docs/shop/react-checkout#a-cart-for-the-whole-storefront) wraps it for you.

## Handle errors

Mutations throw `CommerceError` when they cannot be applied. When the buyer can
fix it, `error.problem.cart` carries the Cart as it is:

```ts
import { CommerceError } from "@orbcart/client";

try {
  await cart.enterCode(input.value);
} catch (error) {
  if (error instanceof CommerceError && error.problem.code === "code_invalid") {
    showFieldHint("This code doesn't apply to your bag.");
  } else {
    throw error;
  }
}
```

See [Errors](/docs/cart/errors) for every code and what to do.

[Turn the Cart into a Quote →](/docs/shop/quotes)