All Features / Shopping Cart System
4-6 hours
intermediate

Shopping Cart System

Guest checkout + localStorage + magic link auth + cart migration

e-commercesaasmarketplace

Paste this into Claude Code to start implementing

πŸ”§Works With

This spec is compatible with:

The implementation prompt includes guidance for these tech stacks.

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:

  1. Map your data models first - Show AI your Product and User schemas before implementing
  2. Break into 3 phases - (1) localStorage cart, (2) magic link auth, (3) cart migration
  3. Test merge logic extensively - This is where most bugs happen (duplicate items, quantity conflicts)
  4. 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:

  1. Guest checkout - Email + shipping address only
  2. 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:

  1. On login, check for localStorage cart
  2. If exists, compare with server-side cart
  3. Merge strategy (configurable):
    • Keep higher quantity for duplicates
    • Preserve both (let user choose)
    • Server cart always wins
  4. Show confirmation modal before merge
  5. 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:

  1. What does my current Product and User data model look like? (Show me the relevant schema)
  2. Do I already have an authentication system? If so, how does it work?
  3. What payment processor am I planning to use?
  4. How should we handle inventoryβ€”real-time checks or eventual consistency?
  5. 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

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!

Need Implementation Help?

Get expert guidance on architecture, security, and best practices.

Book a Consultation
Shopping Cart System | Claude Code Implementation Guide | HashBuilds