← Back to Lego Blocks

E-Commerce Platform

Full-stack online store solution with product catalog, shopping cart, secure checkout, payment processing, order management, and inventory tracking for scalable retail operations.

Product Management
Stripe Integration
Order Tracking

Scope Overview

Comprehensive e-commerce platform covering the complete online shopping experience from browsing to fulfillment.

Must-Have Features

  • Product catalog with categories, variants (size, color), and pricing tiers
  • Shopping cart with add/remove/update quantity operations
  • Secure checkout flow with guest checkout and saved addresses
  • Stripe payment integration with card processing and webhooks
  • Order management with status tracking (pending, processing, shipped, delivered)
  • Inventory tracking with stock levels and low-stock alerts
  • Customer accounts with order history and saved payment methods
  • Admin dashboard for product, order, and customer management

Nice-to-Have Features

  • Product search with filters (category, price range, rating)
  • Discount codes and promotional campaigns
  • Product reviews and ratings system
  • Wishlist and saved items functionality
  • Email notifications for order confirmation and shipping updates
  • Multi-currency support with exchange rates
  • Tax calculation based on shipping location
  • Abandoned cart recovery via email

System Architecture

Three-tier Next.js full-stack application with server-side rendering, API routes, and PostgreSQL database.

Frontend Layer

Next.js 15 + React

  • Server components for product catalog pages (SSR for SEO)
  • Client components for cart, checkout, and interactive UI
  • React Context for global cart state management
  • TanStack Query for client-side data caching
  • Optimistic updates for instant cart feedback
  • Responsive design with mobile-first approach

Backend Layer

Next.js API Routes / Node.js

  • REST API endpoints for products, cart, orders, and customers
  • Server actions for mutations (add to cart, place order)
  • Stripe API integration for payment processing
  • Webhook handlers for payment confirmation
  • Authentication with NextAuth.js or custom JWT
  • Middleware for protected routes and admin access

Data Layer

PostgreSQL + Redis

  • PostgreSQL for transactional data (products, orders, customers)
  • Prisma ORM for type-safe database queries
  • Redis for session storage and cart caching
  • Database indexes on product_id, order_id, customer_email
  • Foreign key constraints for data integrity
  • Migrations for schema versioning

Product Catalog Design

Flexible data model supporting products with variants, multiple images, categories, and tags for rich browsing experience.

Product Model

Core product entity with variants and pricing

  • name, slug, description, price, compare_at_price
  • category_id (FK), brand, sku, weight, dimensions
  • is_active, is_featured flags for visibility
  • metadata JSON for custom attributes
  • created_at, updated_at timestamps

Product Variants

Size, color, and style variations

  • product_id (FK), sku, name (e.g., 'Large / Blue')
  • price override if different from base product
  • stock_quantity, low_stock_threshold
  • option1_name, option1_value (size: Large)
  • option2_name, option2_value (color: Blue)

Product Images

Multiple images per product

  • product_id (FK), url, alt_text
  • position for display ordering
  • is_primary flag for main image
  • File storage in S3/Cloudinary with CDN
  • Thumbnail and optimized versions

Categories & Tags

Hierarchical organization

  • Categories with parent_id for nesting
  • Tags for flexible filtering (e.g., 'new', 'sale')
  • Many-to-many product_tags join table
  • SEO-friendly slugs for URLs
  • Category images and descriptions

Database Schema

PostgreSQL schema with 8 core tables covering products, customers, orders, and shopping cart functionality.

products

Core product catalog

id (UUID, PK)
name, slug, description (TEXT)
price (DECIMAL), compare_at_price
category_id (FK → categories)
brand, sku, weight, dimensions
is_active, is_featured (BOOLEAN)
metadata (JSONB)
created_at, updated_at (TIMESTAMP)

product_variants

Product variations (size, color)

id (UUID, PK)
product_id (FK → products)
sku, name (e.g., 'Large / Blue')
price (DECIMAL, nullable override)
stock_quantity (INTEGER)
low_stock_threshold (INTEGER)
option1_name, option1_value
option2_name, option2_value
is_active (BOOLEAN)

customers

Customer accounts

id (UUID, PK)
email (UNIQUE), password_hash
first_name, last_name, phone
is_verified, is_active (BOOLEAN)
stripe_customer_id
created_at, updated_at

addresses

Shipping and billing addresses

id (UUID, PK)
customer_id (FK → customers)
type (ENUM: shipping, billing)
first_name, last_name
address_line1, address_line2
city, state, postal_code, country
phone
is_default (BOOLEAN)

orders

Customer orders

id (UUID, PK)
order_number (UNIQUE, generated)
customer_id (FK → customers)
status (ENUM: pending, processing, shipped, delivered, cancelled)
subtotal, tax, shipping, total (DECIMAL)
currency (VARCHAR(3))
shipping_address_id, billing_address_id (FK)
payment_intent_id (Stripe)
notes (TEXT)
created_at, updated_at

order_items

Line items per order

id (UUID, PK)
order_id (FK → orders)
product_id (FK → products)
variant_id (FK → product_variants, nullable)
quantity (INTEGER)
price (DECIMAL, snapshot at time of order)
discount_amount
total (DECIMAL)

carts

Shopping cart (session or user)

id (UUID, PK)
customer_id (FK → customers, nullable for guest)
session_id (for guest carts)
expires_at (TIMESTAMP)
created_at, updated_at

cart_items

Items in shopping cart

id (UUID, PK)
cart_id (FK → carts)
product_id (FK → products)
variant_id (FK → product_variants, nullable)
quantity (INTEGER)
added_at (TIMESTAMP)

Database Indexes & Constraints

  • • Index on products(slug), products(category_id)
  • • Index on orders(customer_id, status)
  • • Index on customers(email)
  • • Index on cart_items(cart_id, product_id)
  • • Foreign key constraints for referential integrity
  • • Unique constraint on customers(email)
  • • Check constraint: order total = subtotal + tax + shipping
  • • Trigger to update product_variants.stock_quantity on order

Shopping Cart Logic

Core cart operations with optimistic updates, validation, and persistent storage for both authenticated and guest users.

Add to Cart

Add product with variant and quantity

1. Client: addToCart(productId, variantId?, quantity)
2. Check if product+variant already in cart
3. If exists: UPDATE cart_items SET quantity = quantity + ?
4. If new: INSERT INTO cart_items
5. Return updated cart with item count and subtotal
6. Update React Context and show toast notification

Update Quantity

Change quantity of existing cart item

1. Client: updateCartItem(cartItemId, newQuantity)
2. Validate newQuantity > 0 and <= stock_quantity
3. UPDATE cart_items SET quantity = ?
4. Recalculate cart subtotal
5. Return updated cart
6. Optimistic update in UI before server response

Remove from Cart

Delete item from shopping cart

1. Client: removeCartItem(cartItemId)
2. DELETE FROM cart_items WHERE id = ?
3. Recalculate cart subtotal
4. Return updated cart
5. Show undo option for 5 seconds
6. Animate item removal in UI

Get Cart

Fetch current cart with all items

1. Client: getCart() on page load
2. If logged in: SELECT by customer_id
3. If guest: SELECT by session_id from cookie
4. JOIN products, variants, images
5. Calculate subtotal = SUM(price * quantity)
6. Return cart with items array and totals

Cart State Management

  • • React Context for global cart state across components
  • • Redis cache for session carts (30-day TTL)
  • • PostgreSQL for authenticated user carts (persistent)
  • • Merge guest cart into user cart on login
  • • Real-time stock validation before checkout
  • • Automatic cart cleanup for expired guest carts (cron job)

Checkout Flow

Four-step checkout process optimized for conversion with progress indicator and validation at each step.

1

Cart Review

Review items, apply discount codes

  • Display all cart items with images and quantities
  • Show subtotal, estimated shipping, estimated tax
  • Input field for discount/promo codes
  • Validate code against promotions table
  • Apply discount and recalculate total
  • Continue to shipping button
2

Shipping Address

Collect or select shipping address

  • Show saved addresses for logged-in users
  • Address form: name, address, city, state, zip, country
  • Real-time address validation (e.g., Google Places API)
  • Calculate shipping cost based on weight and destination
  • Save address to customer profile option
  • Continue to payment button
3

Payment Processing

Stripe Elements for secure card input

  • Embed Stripe CardElement with custom styling
  • Billing address same as shipping checkbox
  • Create Stripe Payment Intent on submit
  • Handle 3D Secure (SCA) if required
  • Show loading state during payment processing
  • On success: create order, clear cart, redirect to confirmation
4

Order Confirmation

Display order summary and next steps

  • Thank you message with order number
  • Order summary: items, shipping address, total
  • Send confirmation email with order details
  • Track order button linking to order status page
  • Recommended products section
  • Download invoice/receipt option

Guest Checkout Support

Allow customers to complete purchase without creating an account for faster conversion:

  • • Email address required for order confirmation and tracking
  • • Optional account creation after successful order
  • • Send magic link to email for order status access
  • • Store guest orders with email as identifier
  • • Prompt to save address and payment method for next time

Payment Processing

Stripe-powered payment system with webhooks for reliable order creation and PCI-compliant security.

Stripe Integration

Secure payment processing with Stripe

  • Stripe Elements for PCI-compliant card input
  • Support for credit/debit cards via Payment Intents API
  • 3D Secure (SCA) for European customers
  • Payment method saved for future purchases (optional)
  • Refunds and partial refunds via Stripe Dashboard or API
  • Test mode for development with test card numbers

Webhook Handling

Real-time payment event processing

  • payment_intent.succeeded: Create order, send confirmation
  • payment_intent.payment_failed: Show error, notify customer
  • charge.refunded: Update order status to 'refunded'
  • Webhook signature verification for security
  • Idempotent handlers to prevent duplicate processing
  • Retry logic with exponential backoff

Security & Compliance

PCI DSS compliance and fraud prevention

  • Never store raw card numbers (handled by Stripe)
  • HTTPS only for all payment pages
  • Stripe Radar for fraud detection
  • Address Verification System (AVS) checks
  • CVV verification required
  • 3D Secure 2 for Strong Customer Authentication (SCA)

Order Creation Flow

Transaction workflow from payment to order

  • 1. Create Payment Intent with order amount
  • 2. Client confirms payment with Stripe.js
  • 3. Webhook receives payment_intent.succeeded
  • 4. BEGIN TRANSACTION: Create order record
  • 5. Create order_items from cart
  • 6. Decrement product_variants.stock_quantity
  • 7. Clear customer's cart
  • 8. COMMIT TRANSACTION
  • 9. Send order confirmation email
  • 10. Redirect customer to order success page

Environment Variables

Client-side (Next.js):

  • NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY

Server-side (API routes):

  • STRIPE_SECRET_KEY
  • STRIPE_WEBHOOK_SECRET

REST API Endpoints

12 core API routes built with Next.js API Routes or Server Actions for products, cart, checkout, and orders.

GET/api/products

List products with filters and pagination

?category=shoes&minPrice=50&maxPrice=200&page=1&limit=20

GET/api/products/[slug]

Get product details by slug

Returns product with variants, images, and reviews

GET/api/cart

Get current cart for user or session

Returns cart with items array and calculated totals

POST/api/cart/add

Add product to cart

Body: { productId, variantId?, quantity }

PUT/api/cart/items/[id]

Update cart item quantity

Body: { quantity: 3 }

DELETE/api/cart/items/[id]

Remove item from cart

Returns updated cart

POST/api/checkout/calculate

Calculate shipping and tax

Body: { cartId, shippingAddressId }

POST/api/checkout/create-payment-intent

Create Stripe Payment Intent

Body: { cartId, shippingAddressId, billingAddressId }

POST/api/webhooks/stripe

Handle Stripe webhook events

Signature verification with STRIPE_WEBHOOK_SECRET

GET/api/orders

List customer orders

?status=shipped&page=1&limit=10

GET/api/orders/[id]

Get order details with items

Returns order with tracking info

POST/api/admin/products

Create new product (admin only)

Body: { name, price, categoryId, variants[], images[] }

API Design Patterns

  • • RESTful conventions with proper HTTP methods
  • • JWT authentication for protected routes
  • • Pagination with page and limit query params
  • • Consistent error responses with status codes
  • • Rate limiting on checkout and admin endpoints
  • • Response caching for product catalog (ISR)

User Interface Pages

Complete Next.js application with storefront, checkout, customer account, and admin dashboard interfaces.

Storefront Pages

/products

Product listing with filters, search, and pagination

/products/[slug]

Product detail with variant selector and add to cart

/categories/[slug]

Category page with filtered products

/cart

Shopping cart review with item management

/search

Search results with autocomplete suggestions

Checkout Flow

/checkout/cart

Cart review with discount code input

/checkout/shipping

Shipping address form with saved addresses

/checkout/payment

Stripe Elements for card payment

/checkout/confirmation

Order success page with order number

Customer Account

/account/dashboard

Order history and account overview

/account/orders/[id]

Order details with tracking info

/account/addresses

Manage saved shipping addresses

/account/payment-methods

Manage saved cards (Stripe)

/account/settings

Profile settings and email preferences

Admin Dashboard

/admin/products

Product list with edit/delete actions

/admin/products/new

Create product with variants and images

/admin/orders

Order management with status updates

/admin/customers

Customer list and details

/admin/analytics

Sales reports and product performance

UI Components & Libraries

  • • shadcn/ui for consistent design system
  • • React Hook Form for checkout forms
  • • TanStack Table for product/order tables
  • • Stripe Elements for payment input
  • • Framer Motion for animations
  • • Next.js Image for optimized product images
  • • Responsive design with Tailwind CSS
  • • Dark mode support

Production Ready Benefits

Key Benefits

  • Complete online store from product catalog to order fulfillment
  • Secure payment processing with Stripe (PCI compliant)
  • Guest checkout for faster conversion rates
  • Inventory tracking with low-stock alerts
  • Mobile-responsive design for shopping on any device
  • SEO-optimized product pages with server-side rendering
  • Order management dashboard for tracking and fulfillment
  • Email notifications for order confirmation and shipping

Definition of Done

  • All database tables created with indexes and constraints
  • Cart operations (add, update, remove) with optimistic updates
  • Four-step checkout flow with Stripe integration
  • Webhook handler for payment_intent.succeeded event
  • Customer account with order history
  • Admin dashboard for product and order management
  • Product search with filters (category, price range)
  • Responsive UI tested on desktop and mobile

Ready to Launch Your Store?

This e-commerce platform provides everything you need to start selling online, from product management to secure payment processing and order fulfillment.

Next.js 15PostgreSQLStripeRedisPrisma ORM

Build Your Next Product With AI Expertise

Experience the future of software development. Let our GenAI platform accelerate your next project.

Schedule a Free AI Blueprint Session