🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101

Amazon clone: multi-seller marketplace

An online marketplace where many sellers list products and buyers search, add to cart, pay (in test mode) and track orders that are split per seller, with verified-buyer reviews.

Advanced⏱ 35–45 hours★ 10 detailed steps with codeNext.jsTypeScriptPostgreSQLPrismaRazorpay (test mode)

Educational project inspired by Amazon. Skills101 is not affiliated with Amazon. Give your app its own name and logo, and do not copy their branding or content.

What you’ll learn

  • ◆Modelling a real marketplace: sellers, products, orders split per seller
  • ◆Database transactions so stock never goes negative
  • ◆Payment gateway integration with server-side signature checks
  • ◆PostgreSQL full-text search

What you’ll build

  • ✓Buyer, seller and admin roles
  • ✓Product search with filters, sorting and full-text matching
  • ✓Cart that survives login, checkout and test payments
  • ✓Seller dashboard, order tracking and verified reviews

Before you start

What you need

  • •React and Next.js basics, and some SQL (JOIN, GROUP BY).
  • •Node.js 20+, PostgreSQL (or Docker).
  • •A free Razorpay account to get TEST mode keys. Test mode never moves real money.

How it fits together

  1. 1Next.js renders pages and runs server actions; Prisma talks to PostgreSQL.
  2. 2A buyer's order is one Order with one SubOrder per seller, so each seller ships and updates status independently.
  3. 3Prices are stored as integers in paise and copied into order items at checkout, so later price changes never alter old orders.
  4. 4Payment: server creates a Razorpay order → browser checkout → server verifies the signature (and a webhook confirms) → order marked paid.

Project structure

folders
bazaarly/
├─ prisma/schema.prisma, seed.ts
├─ src/app/
│  ├─ page.tsx, s/page.tsx (search), p/[slug]/page.tsx
│  ├─ cart/page.tsx, checkout/page.tsx
│  ├─ orders/page.tsx, orders/[id]/page.tsx
│  ├─ seller/ (dashboard, products, orders)
│  └─ api/razorpay/webhook/route.ts
└─ src/lib/ (db, auth, cart, money, search, payments)

Step-by-step guide

  1. Step 1

    Plan the marketplace and its roles

    Goal: A list of roles, what each can do, and your own app name.

    A marketplace has three kinds of users. Buyers browse, buy and review. Sellers list products, manage stock and ship their part of each order. Admins approve sellers and remove bad listings. Write one table: role → allowed actions. This drives every permission check later.

    v1: seller sign-up and product listing, search, product page, cart, checkout with test payment, order tracking, reviews. Later: returns, coupons, recommendations.

    Name it yourself (“Bazaarly”). Use your own logo and colours. Do not copy Amazon's logo, product photos or descriptions; use your own photos or images with a free licence and credit them.

    ✅ Check it works

    You can answer “who can change an order's status?” from your table.

  2. Step 2

    Design the database: money in paise, orders split per seller

    Goal: A schema that handles many sellers, price history and stock correctly.

    Store prices as integers in paise (₹499.00 = 49900). Floating-point numbers cannot represent money exactly (0.1 + 0.2 ≠ 0.3), and rounding errors in totals are a classic bug.

    A buyer's cart can contain items from three sellers. Create one Order (what the buyer paid) and one SubOrder per seller (what each seller must ship). Each OrderItem copies the product name and price at checkout time; if the seller changes the price tomorrow, old orders stay correct.

    Add a stock integer on Product and a database CHECK that it is never negative (add it in the SQL migration: ALTER TABLE "Product" ADD CONSTRAINT stock_ok CHECK (stock >= 0)). The database is your last line of defence.

    prisma/schema.prisma (core models)
    model Product {
      id          String   @id @default(cuid())
      sellerId    String
      seller      Seller   @relation(fields: [sellerId], references: [id])
      slug        String   @unique
      name        String
      description String
      category    String
      pricePaise  Int
      stock       Int
      ratingSum   Int      @default(0)
      ratingCount Int      @default(0)
      active      Boolean  @default(true)
      images      ProductImage[]
      @@index([category, pricePaise])
    }
    
    model Order {
      id          String     @id @default(cuid())
      buyerId     String
      totalPaise  Int
      status      String     // PENDING_PAYMENT | PAID | CANCELLED
      razorpayId  String?    @unique
      address     Json
      subOrders   SubOrder[]
      createdAt   DateTime   @default(now())
    }
    
    model SubOrder {
      id       String      @id @default(cuid())
      orderId  String
      order    Order       @relation(fields: [orderId], references: [id])
      sellerId String
      status   String      // PLACED | PACKED | SHIPPED | DELIVERED
      items    OrderItem[]
    }
    
    model OrderItem {
      id         String   @id @default(cuid())
      subOrderId String
      subOrder   SubOrder @relation(fields: [subOrderId], references: [id])
      productId  String
      name       String   // copied at checkout
      pricePaise Int      // copied at checkout
      qty        Int
    }

    ✅ Check it works

    You can explain why OrderItem copies name and pricePaise instead of only linking to Product.

  3. Step 3

    Seller onboarding and product listing

    Goal: Sellers can register a store and add products with images, validated on the server.

    A user becomes a seller by creating a Seller profile (store name, GSTIN optional, pickup address); admins approve it. Only approved sellers see the listing form.

    Validate every field on the server with zod, even if the form validates too; anyone can send requests without your form. Convert the rupee input to paise once, at the boundary.

    Resize uploaded images with sharp to 1000px WebP and a 300px thumbnail; reject files over 5 MB or that are not images. Store them in object storage or uploads/ outside the code folder.

    src/app/seller/products/actions.ts
    'use server'
    import { z } from 'zod'
    import { db } from '@/lib/db'
    import { requireSeller } from '@/lib/auth'
    import { slugify } from '@/lib/slug'
    
    const ProductInput = z.object({
      name: z.string().trim().min(3).max(120),
      description: z.string().trim().min(20).max(5000),
      category: z.enum(['electronics', 'books', 'fashion', 'home', 'toys']),
      priceRupees: z.coerce.number().positive().max(10_00_000),
      stock: z.coerce.number().int().min(0).max(100_000),
    })
    
    export async function createProduct(form: FormData) {
      const seller = await requireSeller()                 // throws unless an approved seller
      const p = ProductInput.parse(Object.fromEntries(form))
      return db.product.create({
        data: {
          sellerId: seller.id, name: p.name, description: p.description, category: p.category,
          pricePaise: Math.round(p.priceRupees * 100), stock: p.stock,
          slug: slugify(p.name) + '-' + Math.random().toString(36).slice(2, 7),
        },
      })
    }

    ✅ Check it works

    Posting a negative price or a 2-character name with curl is rejected even though the form would block it.

  4. Step 4

    Search with PostgreSQL full-text search

    Goal: Searching “wireless earphone” finds “Wireless Earphones with Mic”, with filters and sorting.

    LIKE "%text%" cannot use normal indexes and does not understand word forms. PostgreSQL full-text search converts text into a tsvector (normalised words) and matches it against a tsquery, using a GIN index. It handles plurals (“earphone” matches “earphones”) and ranks results.

    Add a generated column and an index in a SQL migration (npx prisma migrate dev --create-only, then edit the SQL). Query it with $queryRaw and tagged parameters, which are safe from SQL injection.

    Keep filters (category, price range, rating) and sort in the URL so search pages are shareable and the back button works.

    prisma/migrations/..._search/migration.sql
    ALTER TABLE "Product" ADD COLUMN search tsvector
      GENERATED ALWAYS AS (
        setweight(to_tsvector('english', coalesce(name, '')), 'A') ||
        setweight(to_tsvector('english', coalesce(description, '')), 'B')
      ) STORED;
    CREATE INDEX product_search_idx ON "Product" USING GIN (search);
    
    -- query (from Prisma: db.$queryRaw with q as a parameter)
    SELECT id, name, "pricePaise", ts_rank(search, websearch_to_tsquery('english', $1)) AS rank
    FROM "Product"
    WHERE active AND search @@ websearch_to_tsquery('english', $1)
    ORDER BY rank DESC
    LIMIT 24;

    ✅ Check it works

    EXPLAIN ANALYZE on the query shows “Bitmap Index Scan on product_search_idx”.

  5. Step 5

    Cart that survives login

    Goal: Guests can add to cart; when they log in, their guest cart merges into their account cart.

    Guests keep the cart in a cookie or localStorage as [{productId, qty}]. Logged-in users have CartItem rows. On login, merge: for each guest item, add its quantity to the account cart (capped by stock), then clear the guest cart.

    Never trust prices from the browser. The cart page always reloads current prices and stock from the database and shows a notice if something changed (“Price dropped to ₹1,299” or “Only 2 left”).

    Group the cart display by seller, the same way the order will be split.

    src/lib/cart.ts
    export async function mergeGuestCart(userId: string, guest: { productId: string; qty: number }[]) {
      for (const g of guest.slice(0, 50)) {
        const product = await db.product.findUnique({ where: { id: g.productId }, select: { stock: true, active: true } })
        if (!product?.active) continue
        const existing = await db.cartItem.findUnique({ where: { userId_productId: { userId, productId: g.productId } } })
        const qty = Math.min(product.stock, (existing?.qty ?? 0) + Math.max(1, Math.floor(g.qty)))
        if (qty <= 0) continue
        await db.cartItem.upsert({
          where: { userId_productId: { userId, productId: g.productId } },
          update: { qty },
          create: { userId, productId: g.productId, qty },
        })
      }
    }

    ✅ Check it works

    Add 2 items as a guest, log in: the account cart contains them plus anything that was already there.

  6. Step 6

    Checkout: reserve stock and split the order in one transaction

    Goal: Placing an order reduces stock atomically and creates one sub-order per seller.

    Two buyers can click “Place order” for the last unit at the same moment. If you read stock, check it, then write, both can pass the check. Instead, use a conditional update: “decrease stock by qty WHERE stock >= qty”. The database applies it atomically; if it updated 0 rows, the item sold out.

    Do everything inside db.$transaction: decrement each product, create the Order, SubOrders and OrderItems, clear the cart. If any step throws, everything rolls back, including stock.

    The order starts as PENDING_PAYMENT. If payment does not complete within 15 minutes, a scheduled job cancels it and returns the stock.

    src/lib/checkout.ts
    export async function placeOrder(buyerId: string, address: Address) {
      return db.$transaction(async (tx) => {
        const cart = await tx.cartItem.findMany({ where: { userId: buyerId }, include: { product: true } })
        if (!cart.length) throw new Error('Cart is empty')
    
        for (const item of cart) {
          const res = await tx.product.updateMany({
            where: { id: item.productId, active: true, stock: { gte: item.qty } },
            data: { stock: { decrement: item.qty } },
          })
          if (res.count === 0) throw new Error(item.product.name + ' just sold out')
        }
    
        const bySeller = Map.groupBy(cart, (i) => i.product.sellerId)
        const total = cart.reduce((sum, i) => sum + i.product.pricePaise * i.qty, 0)
        const order = await tx.order.create({
          data: {
            buyerId, totalPaise: total, status: 'PENDING_PAYMENT', address,
            subOrders: { create: [...bySeller].map(([sellerId, items]) => ({
              sellerId, status: 'PLACED',
              items: { create: items.map((i) => ({ productId: i.productId, name: i.product.name, pricePaise: i.product.pricePaise, qty: i.qty })) },
            })) },
          },
        })
        await tx.cartItem.deleteMany({ where: { userId: buyerId } })
        return order
      })
    }

    ✅ Check it works

    Set a product's stock to 1 and place two orders at the same time (two tabs, or a script): exactly one succeeds.

    ⚠️ Common mistakes

    • Map.groupBy needs Node 21+; on Node 20 group with a plain loop.
  7. Step 7

    Take payments with Razorpay in test mode

    Goal: Buyers pay with Razorpay's test card or UPI, and only the server marks orders as paid.

    Flow: your server creates a Razorpay order for totalPaise (amount is in paise) and saves its id on your Order. The browser opens Razorpay Checkout with that id. After payment, Razorpay returns razorpay_payment_id, razorpay_order_id and razorpay_signature to the browser, which posts them to your server.

    The server recomputes the signature: HMAC-SHA256 of order_id + "|" + payment_id with your key secret, and compares. Only if it matches is the order marked PAID. Never mark an order paid just because the browser says so.

    Also add the payment.captured webhook (with its own webhook secret). If the buyer closes the tab right after paying, the webhook still marks the order paid. Make both paths idempotent: marking an already-paid order paid again does nothing.

    src/lib/payments.ts
    import { createHmac, timingSafeEqual } from 'node:crypto'
    
    export function validPaymentSignature(orderId: string, paymentId: string, signature: string) {
      const expected = createHmac('sha256', process.env.RAZORPAY_KEY_SECRET!)
        .update(orderId + '|' + paymentId)
        .digest('hex')
      const a = Buffer.from(expected), b = Buffer.from(signature)
      return a.length === b.length && timingSafeEqual(a, b)
    }
    
    export async function markPaid(razorpayOrderId: string) {
      // idempotent: only PENDING_PAYMENT orders move to PAID
      await db.order.updateMany({ where: { razorpayId: razorpayOrderId, status: 'PENDING_PAYMENT' }, data: { status: 'PAID' } })
    }

    ✅ Check it works

    With Razorpay test keys, a test payment marks the order PAID; posting a made-up signature returns an error and leaves it unpaid.

    ⚠️ Common mistakes

    • Putting the key secret in client code or a NEXT_PUBLIC_ variable. Only the key id is public.
  8. Step 8

    Seller dashboard and order tracking

    Goal: Sellers move their sub-orders through PACKED → SHIPPED → DELIVERED; buyers see each part's status.

    The seller dashboard lists sub-orders where sellerId is theirs and the parent order is PAID, newest first. A seller must never see or change another seller's sub-orders; filter by seller id in every query, not only in the UI.

    Allow only valid transitions (PLACED→PACKED→SHIPPED→DELIVERED). Store a timestamp for each and show the buyer a simple timeline per seller (“Shipped by Ravi Electronics on 3 Dec”).

    Add low-stock warnings on the seller dashboard and a daily sales chart (sum of item totals per day).

    ✅ Check it works

    Seller A cannot change the status of seller B's sub-order even by editing the request in DevTools.

  9. Step 9

    Reviews only from verified buyers

    Goal: Product pages show trustworthy ratings that cannot be spammed.

    Allow a review only if the user has a DELIVERED order item for that product, and only one review per (user, product) with a unique constraint. Show a “Verified purchase” badge.

    Keep ratingSum and ratingCount on Product and update them in the same transaction as inserting the review. The product page then shows the average without scanning all reviews.

    Let admins hide abusive reviews; hiding must also subtract from the sums.

    ✅ Check it works

    A user who has not received the product sees “Only buyers can review”; a second review from the same user is rejected.

  10. Step 10

    Seed, deploy and present

    Goal: A live marketplace with demo sellers and products, and a README that explains the hard parts.

    Seed 3 sellers and 60 products with @faker-js/faker for names and your own or freely licensed images. Create demo logins for a buyer and a seller and show them in the README so reviewers can try both sides.

    Deploy the app and a managed PostgreSQL. Add the Razorpay TEST keys and webhook secret as environment variables; make it obvious on the checkout page that it is test mode.

    README: the schema diagram, how stock is protected (conditional update + CHECK constraint), the payment flow diagram, and “Educational project inspired by Amazon. Not affiliated.”

    ✅ Check it works

    A reviewer can log in as the demo buyer, buy from two sellers, and log in as one seller to ship only their part.

🚀 Make it stand out

  • +Coupons with usage limits
  • +Returns and refunds in test mode
  • +“Customers also bought” from order co-occurrence
  • +Invoice PDF with GST breakup