<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/i-had-no-idea-building-a-cart-was-this-deep-ptxpyjvcu" -->

---
title: I Had No Idea Building a Cart Was This Deep | daily.dev
description: A developer shares hard-won lessons from building a full cart experience for a Creator Store, upgrading from a single-product Stripe redirect. Key technical...
canonical: https://daily.dev/posts/i-had-no-idea-building-a-cart-was-this-deep-ptxpyjvcu
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: I Had No Idea Building a Cart Was This Deep | daily.dev
og:description: A developer shares hard-won lessons from building a full cart experience for a Creator Store, upgrading from a single-product Stripe redirect. Key technical...
og:url: https://daily.dev/posts/i-had-no-idea-building-a-cart-was-this-deep-ptxpyjvcu
og:image: https://api.daily.dev/og/posts/pTxpYjvcu.png
og:image:alt: I Had No Idea Building a Cart Was This Deep
og:image:width: 1200
og:image:height: 630
og:locale: en
---

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

# I Had No Idea Building a Cart Was This Deep

**[Developer's Journey](https://daily.dev/sources/devjourney)** · [@drakeze](https://daily.dev/drakeze) · 4 min read · 144 upvotes · 46 comments

## Summary

A developer shares hard-won lessons from building a full cart experience for a Creator Store, upgrading from a single-product Stripe redirect. Key technical decisions covered include: choosing localStorage over a database-backed cart to avoid auth friction, using React's useSyncExternalStore to sync cart state across browser tabs, implementing a non-destructive 'Add to Cart' UX pattern, handling Stripe webhook duplicates with two-layer idempotency (unique stripeEventId constraint + composite sessionKey), fixing floating-point rounding when splitting payments across items, and using a 409 Conflict pattern to filter already-owned products before they reach Stripe.

## Content

Building an "Add to Cart" button sounds like a weekend task. It's not.

I recently shipped V1 of my Creator Store, upgrading from a single-product Stripe redirect to a full persistent cart experience with guest support, multi-item checkout, promo codes, duplicate protection, and an account library. Here are the technical decisions that actually mattered, and the ones that nearly broke everything.

## Stripe Sent Me Duplicates, and I Didn't Notice For Days

The first real fork in the road: where does the cart live?

`localStorage` Zero latency, no auth required, guest users can shop freely, no unnecessary DB writes. Downside: siloed to one device, clearable by the user.

**Database-backed** cross-device sync, abandoned cart recovery, full analytics. Downside: every cart interaction requires an auth check, which creates friction before the user has even decided to buy.

I chose `localStorage`. The reasoning: adding an authentication wall to "Add to Cart" kills conversion. The benefit of cross-device sync doesn't outweigh the cost of requiring sign-in just to browse.

## Solving the Ghost Item Problem with `useSyncExternalStore`

The immediate problem with `localStorage`: open two tabs, add an item in one, look at the other, the cart count doesn't update. The user thinks their click didn't register and adds the item again.

Fix: `useSyncExternalStore`. This React hook subscribes to `localStorage` events across all active browser tabs. When the cart updates in any tab, every tab sees it. One source of truth, no stale UI, no confused users.

```
const cart = useSyncExternalStore(
  subscribeToCartStorage,
  getCartSnapshot,
  getServerSnapshot
)
```

## The Non-Destructive "Add to Cart" Pattern

In V1, clicking "Buy" redirected you immediately to Stripe. Fine for a single product. Terrible for a store.

V2 needed a button that confirms without hijacking. The pattern:

1. User clicks → `addItem()` fires in the `useCart` hook
2. Local `justAdded` state flips to `true`
3. Button visually confirms ("✓ In Cart")
4. After 3000ms, `justAdded` resets UI unlocks
5. User keeps browsing

I didn't realize this until it happened in production `ownedProducts` (fetched server-side) and replaces "Add to Cart" with "View in Library" if they already own it. First line of defense against duplicate purchases at the UI layer.

## Stripe Webhooks Will Arrive More Than Once

This caught me. Stripe webhooks are not guaranteed to fire exactly once; they retry on failure, on timeout, and sometimes just because.

With V1 (single product), this was manageable. With V2 (one checkout session → multiple purchase records), it becomes critical.

**Two-layer idempotency:**

1. `stripeEventId`** Constraint:** store every processed event ID in a unique DB column. Duplicate arrives → DB rejects it at the constraint level.
2. **Composite **`sessionKey` `checkoutSessionId_productId`. Because one Stripe session now fulfills multiple items, the session ID alone is no longer unique per record.

If either layer catches a duplicate (Prisma `P2002` on the constraint), we log it and exit cleanly. No double-fulfillment.

## $9.99 ÷ 3 Is Not $3.33

When splitting a payment across multiple items for your internal records, floating-point math will quietly introduce a $0.01 discrepancy that doesn't match Stripe's total.

Fix: the first item in the array absorbs the rounding remainder.

```
const base = Math.floor((totalCents / items.length))
const remainder = totalCents - base * items.length
items[0].amountCents = base + remainder  // e.g. 334
items.slice(1).forEach(i => i.amountCents = base)  // e.g. 333, 333
```

Obvious in hindsight. Not obvious at 3 AM when your fulfillment records are off by a cent.

## Mixed Carts and the 409 Pattern

Users who own some but not all products in their cart need handling at the API level, not the UI level.

The pattern:

- Before creating the Stripe session, fetch the user's owned products.
- If the entire cart is already owned → `409 Conflict`redirect to the library.
- If the cart is mixed → filter out owned items, proceed with unowned, return `removedOwnedProducts` in the response so the frontend can tell the user why their total changed.

Never let owned products reach Stripe. Handle it upstream.

## The Full Technical Breakdown

This is the medium version. The full post with architecture diagrams, the complete `useCart` hook, promo code implementation, and Account Library data model is on the blog:

**→ [blog.drakeze.com](https://blog.drakeze.com)**

Building in public. More posts from this same build session dropping soon.
Still a lot I'm figuring out. If you've built something similar, I'd genuinely love to know how you handled

## Community discussion

Top comments from developers on daily.dev.

**@palalet** · 9 upvotes

> Safe yourself a hassle and store the prices as number of cents, plus second field the number of decimal places. I.e  10.99 will be stored as 1099 and 2. No division problem, always exact match.

**@itsmnthn** · 9 upvotes

> Good read, Just because

**@baptistecrouzet** · 5 upvotes

> 409 Pattern, division, I agree building a cart is not as easy as it looks. Thank you for sharing your experience !

**@fabianletsch** · 4 upvotes

> Have not read the article yet but based on the comments its probably going to be great, just one small nitpick, you said building a cart you thought would be easy, but it really wasn't, then you described like 5 extra features that you also implemented, which made me think: "Duh of course its going to be complicated if you implemented 5 other things, too"
>
>
> Like I said I will read it later but that put me off to the point where i decided to look at the comments if I should read further.
>
>
> All I am trying to say is, I would go with a slightly adjusted opener.
>
>
> I hope this helps, this is not...

**@alwaisy** · 2 upvotes

> i made my first cart sysem in 2021. it took me literally 1 day to understand working and developing/writing my own logic

## Similar posts on daily.dev

- [How to Build an AJAX Cart Drawer in Shopify \(the 2026 Way\)](https://daily.dev/posts/how-to-build-an-ajax-cart-drawer-in-shopify-the-2026-way--3lpuftmec) · freeCodeCamp · 1 upvotes · 0 comments
- [Refactoring a Messy React Workflow: From One Giant Modal to Independent Vertical Slices](https://daily.dev/posts/refactoring-a-messy-react-workflow-from-one-giant-modal-to-independent-vertical-slices-dgsuki7nv) · Medium · 0 upvotes · 0 comments
- [Ecommerce Storefront Explained: Everything You Need to Know Before Starting Your Online Store](https://daily.dev/posts/ecommerce-storefront-explained-everything-you-need-to-know-before-starting-your-online-store-gtkjeszkg) · Netguru · 0 upvotes · 0 comments
- [The Micro-Frontend Evolution: Why We Traded S3 Behaviors for Module Federation \(and What It Cost Us\)](https://daily.dev/posts/the-micro-frontend-evolution-why-we-traded-s3-behaviors-for-module-federation-and-what-it-cost-us--0iigpovli) · Swiggy Bytes · 9 upvotes · 0 comments
- [How to Build a Shadcn Sheet Component in React: Cart and Filter Panel Examples](https://daily.dev/posts/how-to-build-a-shadcn-sheet-component-in-react-cart-and-filter-panel-examples-ns90bg7qt) · freeCodeCamp · 4 upvotes · 0 comments

---

Tags: [#ecommerce](https://daily.dev/tags/ecommerce), [#react](https://daily.dev/tags/react), [#stripe](https://daily.dev/tags/stripe), [#webdev](https://daily.dev/tags/webdev)

[View this post on daily.dev](https://daily.dev/posts/i-had-no-idea-building-a-cart-was-this-deep-ptxpyjvcu)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"DiscussionForumPosting","mainEntityOfPage":"https://daily.dev/posts/i-had-no-idea-building-a-cart-was-this-deep-ptxpyjvcu","headline":"I Had No Idea Building a Cart Was This Deep","text":"A developer shares hard-won lessons from building a full cart experience for a Creator Store, upgrading from a single-product Stripe redirect. Key technical decisions covered include: choosing localStorage over a database-backed cart to avoid auth friction, using React's useSyncExternalStore to sync cart state across browser tabs, implementing a non-destructive 'Add to Cart' UX pattern, handling Stripe webhook duplicates with two-layer idempotency (unique stripeEventId constraint + composite sessionKey), fixing floating-point rounding when splitting payments across items, and using a 409 Conflict pattern to filter already-owned products before they reach Stripe.","url":"https://daily.dev/posts/i-had-no-idea-building-a-cart-was-this-deep-ptxpyjvcu","datePublished":"2026-06-10T18:37:07.098Z","dateModified":"2026-07-16T02:12:40.599Z","author":{"@type":"Person","name":"Anthony","url":"https://daily.dev/drakeze","image":"https://media.daily.dev/image/upload/s--11gwAjuC--/f_auto/v1765561095/avatars/avatar_m24lqqCHX4cycLADBIHJ7?_a=BAMAK+ZW0","description":"Full-stack dev | Founder of SorenLab | Building in public | Future polyglot engineer","interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"EndorseAction"},"userInteractionCount":4180}},"image":"https://media.daily.dev/image/upload/s--YxenzYhz--/f_auto/v1781116627/posts/pTxpYjvcu?_a=BAMAMiWQ0","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":144},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":46}],"comment":[{"@type":"Comment","text":"Safe yourself a hassle and store the prices as number of cents, plus second field the number of decimal places. I.e  10.99 will be stored as 1099 and 2. No division problem, always exact match.","datePublished":"2026-06-11T11:58:30.749Z","url":"https://daily.dev/posts/pTxpYjvcu#c-4PdxnJFRy","author":{"@type":"Person","name":"Radek Havelka","url":"https://daily.dev/palalet","image":"https://lh3.googleusercontent.com/a-/ACNPEu-o8MElSN4ROMgrqyjqrarlLqksiGLna5TAfYA1Jw=s100"},"interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":9}},{"@type":"Comment","text":"Good read, Just because","datePublished":"2026-06-11T06:16:28.263Z","url":"https://daily.dev/posts/pTxpYjvcu#c-oc6A54LKc","author":{"@type":"Person","name":"Manthankumar Satani","url":"https://daily.dev/itsmnthn","image":"https://media.daily.dev/image/upload/s--XpFWj1ND--/f_auto/v1749054653/avatars/avatar_iBTDQoV5Y?_a=BAMClqUq0"},"interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":9}},{"@type":"Comment","text":"409 Pattern, division, I agree building a cart is not as easy as it looks. Thank you for sharing your experience !","datePublished":"2026-06-11T09:21:29.988Z","url":"https://daily.dev/posts/pTxpYjvcu#c-tUjDZQD8W","author":{"@type":"Person","name":"Baptiste Crouzet","url":"https://daily.dev/baptistecrouzet","image":"https://avatars0.githubusercontent.com/u/26898487?v=4"},"interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":5}},{"@type":"Comment","text":"Have not read the article yet but based on the comments its probably going to be great, just one small nitpick, you said building a cart you thought would be easy, but it really wasn’t, then you described like 5 extra features that you also implemented, which made me think: “Duh of course its going to be complicated if you implemented 5 other things, too”\nLike I said I will read it later but that put me off to the point where i decided to look at the comments if I should read further.\nAll I am trying to say is, I would go with a slightly adjusted opener.\nI hope this helps, this is not meant as blatant negative criticism :)","datePublished":"2026-06-11T16:46:07.648Z","url":"https://daily.dev/posts/pTxpYjvcu#c-KQVTpvYCX","author":{"@type":"Person","name":"Fabian Letsch","url":"https://daily.dev/fabianletsch","image":"https://lh3.googleusercontent.com/a/ACg8ocKR6BVy_wn23EoOKq7-BlszlcXcLmASlnb7l-GtS-q1bePnkaJf=s96-c"},"interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":4}},{"@type":"Comment","text":"i made my first cart sysem in 2021. it took me literally 1 day to understand working and developing/writing my own logic","datePublished":"2026-06-14T19:52:26.000Z","url":"https://daily.dev/posts/pTxpYjvcu#c-Speh6qyBj","author":{"@type":"Person","name":"Awais Alwaisy","url":"https://daily.dev/alwaisy","image":"https://avatars.githubusercontent.com/u/102944304?v=4"},"interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":2}}],"isPartOf":{"@type":"WebPage","url":"https://daily.dev/squads/devjourney","name":"Developer's Journey"}}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"Developer's Journey","item":"https://daily.dev/squads/devjourney"},{"@type":"ListItem","position":3,"name":"I Had No Idea Building a Cart Was This Deep"}]}
```

