Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 40 ยท Cart and Checkout

Designing the Cart

Design a shopping cart that survives real shoppers. Learn guest and logged-in carts, merging on login, price snapshots, validation and abandoned carts.

The cart looks like the simplest part of a shop: a list of products with quantities. In practice it is a small piece of software with sharp edges. It has to survive a closed tab, follow the shopper from phone to laptop, notice when a price or a stock level changes, and never charge for something the shop cannot deliver.

In this lesson you design the cart as a data structure and as an API. You decide where it lives, what a line item stores, when prices are frozen, how a guest cart merges into an account cart, and how you find the shoppers who left without paying. Money is always stored as integer minor units, as explained in Representing Money Correctly.

A cart is a draft of an order

Think of a cart as an unfinished order. It has an owner, a currency, a list of line items and a few derived totals. It is allowed to be wrong for a while (prices change, items sell out), but it is not allowed to be paid for in a wrong state. Checkout is the moment the draft is validated and turned into an order.

A minimal cart looks like this:

JSON
{
  "id": "cart_8f2a",
  "currency": "USD",
  "customer_id": null,
  "lines": [
    { "id": "line_1", "variant_id": "var_tee_m_blue", "quantity": 2,
      "unit_price": 2500, "title": "Logo tee, M, Blue" }
  ],
  "updated_at": "2026-10-30T09:12:00Z",
  "expires_at": "2026-11-29T09:12:00Z"
}

Notice what is missing: the cart does not store a stored total. Totals are computed from the lines (and promotions, tax and shipping) every time, so they can never drift out of step with the lines.

Line items

A line item connects a cart to one purchasable thing, normally a variant (see Variants and Options). Good line items follow a few rules:

  • One line per distinct purchasable plus options. Adding the same variant twice increases the quantity of the existing line instead of creating a second one.
  • Quantity is a positive integer. Setting it to zero removes the line. Reject fractions, negatives and absurd values (a sensible maximum such as 999 stops mistakes and abuse).
  • Reference, then snapshot. Store the variant_id so you can look up current data, and also a few snapshot fields (title, unit price) so the cart can show what the shopper saw.
  • Custom data goes in a separate field. Engraving text, gift messages and uploaded files belong to the line, and two lines with different custom data are different lines.

Guest carts and customer carts

Most visitors are guests. Forcing a login before adding to the cart loses sales, so a cart must exist before an account does.

Aspect Guest cart Customer cart
Owner An anonymous cart token A customer id
Where the token lives A cookie (or local storage) holding only the cart id Server side, found by customer id
Visible on other devices No Yes
Lifetime Short (days to weeks) Longer (weeks to months)

The cart token must be unguessable, long and random, because anyone who knows it can read the cart. Never use a counter such as cart_1042. Send it in an HttpOnly, Secure, SameSite=Lax cookie when the server renders pages. A single-page front end can keep it in memory plus a cookie.

Where to persist carts

You have three common choices:

  1. Database only. Simple and durable; each change is a write. Fine for most shops.
  2. Cache or key-value store with a database backup. Reads are fast, which helps during peak traffic.
  3. Browser only. Fast and private, but the shop cannot see abandoned carts or follow a shopper across devices, and the shopper can edit prices. If you do this, the server must recompute everything at checkout.

Whichever you choose, treat the cart's prices as untrusted when they come from the browser. The server always recomputes them.

Merging on login

When a guest with a cart signs in and already has a saved cart, you have two carts and must produce one. This is the cart merge, and there is no universally right policy, only a few reasonable ones:

  • Add quantities. If both carts contain the same variant, add them. Cap at available stock and at your per-line maximum.
  • Keep the larger quantity. Avoids doubling when the shopper just logged in on a second device with the same items.
  • Prefer the guest cart. The most recent activity usually reflects intent.

Pick one, document it and test it. Also decide what happens to the old guest cart: delete it, or mark it as merged so analytics can still see it.

flowchart LR
    G["Guest cart<br/>(cookie token)"] --> M{"Login"}
    C["Saved customer cart"] --> M
    M --> R["Merge lines<br/>cap quantities"]
    R --> N["Customer cart<br/>(guest cart retired)"]

Logging in turns two carts into one. The merge rule decides how duplicate lines combine.

Price snapshots: when to freeze a price

Prices change: a sale ends, a supplier raises a cost, a scheduled price kicks in. Your cart has to say when it follows the catalog and when it stops. A practical policy:

  • While the shopper browses and edits the cart, show the current price and recompute on every change.
  • If a price changed since the line was added, show a clear notice ("The price of Logo tee changed from $25.00 to $27.00").
  • At the moment of checkout, lock the totals for the payment attempt. After payment, the order stores a permanent snapshot of every price, discount and tax figure (see The Order Lifecycle).

Never let a later catalog edit change the amount of an order that was already paid.

Validate on every change

Each change to the cart (add, update quantity, remove, apply a code) should run the same checks on the server:

  1. The variant exists and is purchasable (published, not archived).
  2. The quantity is within limits (minimum, maximum, step such as "packs of 6").
  3. Enough stock is available, or backorders are allowed (Inventory Tracking).
  4. The price and currency match the current catalog.
  5. Any shipping restriction (for example a product that cannot ship to the chosen country) still holds.

Return problems as structured data rather than throwing away the whole cart. A good response includes the cart, the computed totals and a list of warnings the interface can show next to specific lines.

Here is a small cart calculator that follows these rules. It merges quantities into one line, clamps to stock, drops zero quantities and recomputes totals from integers:

JS A cart that validates every change

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The cart never stores a total. It stores lines and asks totals() each time, which is the same approach a real server should use.

Abandoned carts

Most carts are never paid for. A cart is abandoned when it has items, a way to reach the shopper (a customer account or an email captured at checkout) and no activity for some period, for example one hour or a day.

To support recovery you need:

  • an updated_at timestamp on the cart, touched on every change;
  • a scheduled job that selects carts older than your threshold, with an email, with no order created from them, and not yet reminded;
  • a recovery link that restores the cart through a signed, unguessable token rather than a plain cart id;
  • a record of which reminders were sent, so no shopper gets the same email twice.

Respect consent: sending marketing reminders to someone who only typed an email at checkout may need permission in some jurisdictions. See GDPR, Consumer Law and Accessibility and Transactional Email and Customer Lifecycle.

Expire old carts as well. Deleting or archiving carts after their expires_at keeps the table small and limits how long personal data hangs around.

Cart API shape

Whether you build a REST API or a GraphQL schema, a cart API tends to look the same. Operations act on the cart and return the whole updated cart, so the client never calculates anything itself.

TEXT
POST   /carts                         create (returns id and token)
GET    /carts/{id}                    read, with totals and warnings
POST   /carts/{id}/lines              add a line {variant_id, quantity}
PATCH  /carts/{id}/lines/{line_id}    change quantity
DELETE /carts/{id}/lines/{line_id}    remove a line
POST   /carts/{id}/discounts          apply a code
POST   /carts/{id}/merge              merge a guest cart (authenticated)

Design notes:

  • Make add-to-cart safe to retry. A double click should not create two lines; merging quantities into the existing line, or accepting an idempotency key (see Idempotency and Reliable Payments), handles it.
  • Use optimistic concurrency (an updated_at or version check) if the same cart is edited from two tabs.
  • Return money as integers plus the currency code, never as formatted strings.
  • Do not let the client send prices. It sends a variant and a quantity.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a cart compute its totals from the line items instead of storing a total?

    Totals are derived data. If you store them next to the lines, any missed update leaves a wrong total. Recomputing each time keeps one source of truth.
  2. 2. A guest signs in and both a guest cart and a saved cart contain the same variant. What should you do?

    Cart merging needs a deliberate, tested rule. Adding quantities with caps (or keeping the larger one) are both reasonable choices, but it must be one rule applied consistently.
  3. 3. Which cart token is the safest to put in a cookie?

    Anyone who knows the token can read the cart, so it must be long and random. Sequential ids can be guessed and enumerated.
  4. 4. The browser sends {variant_id, quantity, price} when adding to the cart. What should the server do with price?

    Client-supplied prices are untrusted and trivially edited. The server derives prices from its own catalog.

Summary

  • A cart is a draft order: lines plus an owner and a currency, with totals computed on demand.
  • Add the same variant to the existing line, keep quantities as bounded positive integers and store both a reference and a snapshot on each line.
  • Guest carts use an unguessable token; logging in triggers a merge with a clear, tested rule.
  • Show current prices while shopping, warn about changes, lock totals for payment and store a permanent snapshot on the order.
  • Validate on the server for every change and return the whole cart with structured warnings.
  • Find abandoned carts with timestamps and a scheduled job, and respect consent and expiry.

Next, turn the cart into a purchase: Checkout Flow and Conversion.