Overview
Production-grade shopping cart with guest checkout, magic link authentication, and cart migration. Handles both logged-out browsing and seamless account creation at checkout.
Use Cases
- E-commerce sites: Full product catalog with guest and authenticated shopping
- Marketplace apps: Multi-vendor platforms with cart management
- SaaS products: Trial-to-paid conversion with cart persistence
When to Use This Pattern
Use this pattern when you need to:
- Allow users to browse and add items without creating an account
- Convert guest users to authenticated users at checkout
- Merge guest cart with user's existing cart after login
- Persist cart across sessions and devices
Pro Tips
Before you start implementing, read these carefully:
- Map your data models first - Show AI your Product and User schemas before implementing
- Break into 3 phases - (1) localStorage cart, (2) magic link auth, (3) cart migration
- Test merge logic extensively - This is where most bugs happen (duplicate items, quantity conflicts)
- Ask AI about edge cases - "What edge cases am I missing?" before implementing
Implementation Phases
Phase 1: Guest Experience
Store cart in localStorage with unique session ID that persists for 30 days.
Key features:
- Handle multiple tabs syncing via storage events
- Show item count badge in header
- Survive page refreshes
- Clear on explicit logout
// Example localStorage structure
{
sessionId: 'uuid-v4',
items: [
{ productId: 123, quantity: 2, addedAt: '2025-12-04T10:30:00Z' }
],
expiresAt: '2026-01-04T10:30:00Z'
}
Phase 2: Cart Operations
Full CRUD operations with optimistic UI updates:
- Add/remove items
- Update quantities (with max limits)
- Apply promo codes with validation
- Calculate tax and shipping in real-time
- Optimistic UI updates with rollback on errors
- Show loading states during mutations
Phase 3: Checkout Flow
Two paths for checkout:
- Guest checkout - Email + shipping address only
- Account creation - Magic link authentication:
- Send email with 6-digit code
- 15-minute expiration
- On successful auth, migrate localStorage cart to database
- Associate cart with user account
Phase 4: Returning Users
Handle cart merging when authenticated user returns:
- On login, check for localStorage cart
- If exists, compare with server-side cart
- Merge strategy (configurable):
- Keep higher quantity for duplicates
- Preserve both (let user choose)
- Server cart always wins
- Show confirmation modal before merge
- Clear localStorage after successful merge
Edge Cases to Handle
Critical Edge Cases
Out of stock during checkout:
- Check inventory before payment
- Show warning if stock changed
- Allow removing out-of-stock items
- Recalculate total
Price changes while in cart:
- Show old price vs new price
- Notify user of changes
- Option to update or remove item
- Lock price at checkout
Expired promo codes:
- Validate code on every mutation
- Show expiration warning
- Remove invalid codes gracefully
- Suggest alternative codes
Concurrent modifications:
- User opens 2 tabs, modifies cart in both
- Use timestamp-based conflict resolution
- Storage events sync tabs
- Server is source of truth for authenticated users
Network failures:
- Retry logic with exponential backoff
- Queue mutations locally
- Show offline indicator
- Sync when connection restored
Cart abandonment:
- localStorage cleanup after 30 days
- Optional: Send reminder emails (requires email capture)
- Track abandonment analytics
- A/B test reminder timing
Tech Stack Recommendations
Minimum Viable Stack
- Framework: Next.js App Router
- State Management: React Context or Zustand
- Storage: localStorage (guest), PostgreSQL (authenticated)
- Auth: NextAuth.js or Clerk
- Email: Resend
Production-Grade Stack
- Framework: Next.js 15 with App Router
- Components: React Server Components for cart display
- Mutations: Server Actions for cart operations
- Database: Prisma + PostgreSQL
- Cache: Redis for session management
- Email: Resend for magic link emails
- Payments: Stripe for checkout (see payment-flow spec)
Architecture Diagram
βββββββββββββββ
β Browser β
β localStorageβ
β (30 days) β
ββββββββ¬βββββββ
β
ββββ Guest User (no auth)
β ββ> Add to cart β localStorage only
β
ββββ Checkout Trigger
β
ββββ Path A: Guest Checkout
β ββ> Email + Shipping β Order created
β
ββββ Path B: Create Account
ββ> Magic link β Migrate cart β User cart in DB
ββββββββββββββββββββ
β Returning User β
β (authenticated) β
ββββββββββ¬ββββββββββ
β
ββββ Has localStorage cart?
β YES β Merge with server cart
β NO β Load server cart
β
ββββ Server Cart (PostgreSQL)
ββ> Synced across devices
Full Implementation Prompt
Copy this prompt to use with Claude Code:
I need to build a production-grade shopping cart system. Before we start coding, help me think through the architecture and edge cases.
The system needs to handle:
- Guest users browsing and adding items (localStorage for 30 days)
- Cart persistence across multiple browser tabs
- Magic link authentication for checkout (email with 6-digit code, 15-minute expiration)
- Seamless cart migration when guest becomes authenticated user
- Merge logic when returning user has both localStorage cart and server-side cart
First, please review my codebase and ask me:
- What does my current Product and User data model look like? (Show me the relevant schema)
- Do I already have an authentication system? If so, how does it work?
- What payment processor am I planning to use?
- How should we handle inventoryβreal-time checks or eventual consistency?
- What happens if a user has the same item in localStorage and server cart? (Higher quantity? Merge? Ask user?)
Then let's discuss these critical edge cases before implementing:
- User checks out as guest, then creates account with same email laterβhow do we reconcile carts?
- Item goes out of stock between adding to cart and checkout
- Price changes while item is in cart (show old price? new price? notify user?)
- Promo code expires during checkout flow
- Network failure during cart migration
- Concurrent modifications (user opens 2 tabs, modifies cart in both)
- User abandons cartβwhen do we clean up localStorage vs send reminder emails?
After we align on these decisions, we'll build this in 3 phases: Phase 1: localStorage cart with full CRUD operations Phase 2: Magic link authentication flow Phase 3: Cart migration and merge logic with comprehensive error handling
Sound good? Let's start by you showing me your existing data models.
Related Feature Specs
- User Authentication - Magic link, OAuth, credentials auth
- Payment Flow - Stripe checkout, webhooks, receipts
- Email System - Transactional emails, templates, queues
- Admin Dashboard - Manage orders, inventory, users
Success Criteria
You've successfully implemented this when:
β Guest users can add/remove items without account β Cart persists across page refreshes and browser sessions β Multiple tabs stay in sync (storage events working) β Magic link authentication works (6-digit code, 15-min expiration) β Cart migrates from localStorage to database on auth β Merge logic handles duplicates correctly β All edge cases have error handling β Checkout flow is smooth for both guest and authenticated users
Common Mistakes to Avoid
β Not handling storage events (tabs out of sync) β Forgetting to clean up expired localStorage carts β No rollback strategy when mutations fail β Inventory checks only at cart add (not at checkout) β No loading states during async operations β Cart merge overwrites without user confirmation β Promo codes not revalidated before payment
Implementation Checklist
- Set up localStorage cart structure
- Implement add/remove/update operations
- Add storage event listeners for tab sync
- Create magic link email template
- Build authentication flow with 6-digit codes
- Design cart merge UI (show conflicts)
- Implement server-side cart operations
- Add inventory validation
- Test concurrent modifications
- Handle network failures gracefully
- Set up cart abandonment cleanup
- Add analytics tracking (cart adds, abandonment rate)
Last Updated: 2025-12-04 Difficulty: Intermediate Estimated Time: 4-6 hours Prerequisites: Basic React, Next.js App Router, database basics
Built with this spec? Add a link to your project and we'll feature it in our showcase!