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

Zomato / Swiggy clone: food delivery with live tracking

Three apps in one: customers order from nearby restaurants, restaurants accept and prepare, delivery partners pick up and deliver while the customer watches them move on a live map.

Advanced⏱ 35–45 hours★ 10 detailed steps with codeNext.jsNode.jsSocket.IOPostgreSQL + PostGISLeafletOpenStreetMap

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

What you’ll learn

  • ◆Location queries with PostGIS (nearby, distance)
  • ◆Order state machines with strict transitions
  • ◆Assigning the nearest free delivery partner safely
  • ◆Live GPS tracking with Socket.IO and maps

What you’ll build

  • ✓Restaurants near you with distance and ETA
  • ✓Menu, cart (one restaurant) and checkout
  • ✓Restaurant panel: new-order alerts, accept, mark ready
  • ✓Delivery partner app and live tracking map

Before you start

What you need

  • •React/Next.js, Node.js, SQL; the WhatsApp guide helps for Socket.IO.
  • •PostgreSQL with the PostGIS extension (Docker image postgis/postgis).
  • •Phones for testing GPS (HTTPS is required for location in browsers; use a tunnel or deploy early).

How it fits together

  1. 1One Next.js app with three areas: /app (customer), /restaurant (panel) and /partner (delivery). Role checks on every server action.
  2. 2PostgreSQL + PostGIS stores restaurant locations as geography points with a spatial index for “nearby” queries.
  3. 3Orders follow a state machine; every change is a conditional update from the expected previous state.
  4. 4Delivery partners' phones send GPS every 5 seconds over Socket.IO; the customer's map receives it through the order's room.

Project structure

folders
fooddash/
├─ db/ (migrations with PostGIS)
├─ src/app/
│  ├─ app/ (home, restaurant/[id], cart, orders/[id])
│  ├─ restaurant/ (orders board, menu)
│  └─ partner/ (go online, current task)
├─ src/lib/ (geo, orders/state-machine, assign, pricing)
└─ realtime/ (Socket.IO server)

Step-by-step guide

  1. Step 1

    Plan the three apps and the order lifecycle

    Goal: Roles, screens and an order state diagram on paper.

    Customer: set location, browse nearby restaurants, menu, cart, pay, track. Restaurant: open/close, menu availability, accept/reject orders, mark ready. Partner: go online, accept a task, pick up, deliver.

    Draw the order states: PLACED → ACCEPTED → PREPARING → READY → PICKED_UP → DELIVERED, and CANCELLED (only from PLACED or ACCEPTED). Next to each arrow write who is allowed to do it.

    Name it (“FoodDash”) and add “Educational project inspired by Zomato and Swiggy. Not affiliated.” in the README. Use your own photos for demo dishes.

    ✅ Check it works

    Your diagram answers “can a restaurant cancel after the food is picked up?” (No.)

  2. Step 2

    Store locations with PostGIS

    Goal: Restaurants and addresses with real coordinates and a spatial index.

    Enable PostGIS (CREATE EXTENSION postgis). Store locations as geography(Point, 4326): longitude and latitude on the Earth, with distances in metres. Remember PostGIS order is (longitude, latitude), the opposite of how people usually say it.

    Add a GIST index on the location column. Without it, “restaurants within 5 km” checks every row; with it, the database only looks nearby.

    Prisma does not support geography columns directly, so declare them as Unsupported("geography(Point,4326)") and query with raw SQL.

    db/migrations/001_geo.sql
    CREATE EXTENSION IF NOT EXISTS postgis;
    
    CREATE TABLE restaurants (
      id           TEXT PRIMARY KEY,
      name         TEXT NOT NULL,
      cuisine      TEXT[] NOT NULL,
      is_open      BOOLEAN NOT NULL DEFAULT false,
      prep_minutes INT NOT NULL DEFAULT 20,
      location     geography(Point, 4326) NOT NULL
    );
    CREATE INDEX restaurants_location_idx ON restaurants USING GIST (location);
    
    -- insert: note the order is (longitude, latitude)
    INSERT INTO restaurants (id, name, cuisine, is_open, location)
    VALUES ('r1', 'Dosa Corner', '{South Indian}', true, ST_SetSRID(ST_MakePoint(75.7873, 26.9124), 4326)::geography);

    ✅ Check it works

    EXPLAIN on a nearby query (next step) shows the GIST index being used.

  3. Step 3

    Show nearby restaurants with distance and ETA

    Goal: The home page lists open restaurants within 5 km, nearest first, with “2.1 km · 30–35 min”.

    Get the customer's location from navigator.geolocation (with permission) or a saved address. Query with ST_DWithin (uses the index) and sort by ST_Distance.

    ETA = prep time + travel time. Estimate travel at about 20 km/h in a city (3 minutes per km) plus 5 minutes for pickup. Show a range, not a single number.

    Closed restaurants appear greyed at the end with “Opens at 6 pm”.

    nearby restaurants
    SELECT id, name, cuisine, prep_minutes,
           round(ST_Distance(location, ST_SetSRID(ST_MakePoint($1, $2), 4326)::geography)) AS metres
    FROM restaurants
    WHERE is_open
      AND ST_DWithin(location, ST_SetSRID(ST_MakePoint($1, $2), 4326)::geography, 5000)
    ORDER BY metres
    LIMIT 50;
    -- $1 = longitude, $2 = latitude
    -- ETA in the app: prep_minutes + 5 + ceil(metres / 1000 * 3)

    ✅ Check it works

    Moving your test location across the city changes the list and distances sensibly.

  4. Step 4

    Menu, cart and checkout rules

    Goal: A cart that holds items from one restaurant, with prices, fees and availability checked on the server.

    Real apps allow one restaurant per order. If the customer adds from a second restaurant, ask: “Replace your cart from Dosa Corner?”.

    Restaurants can mark items unavailable for the day. At checkout the server reloads every item and price; if something changed, it tells the customer instead of charging silently.

    Delivery fee by distance (for example ₹20 up to 3 km, then ₹8 per km), plus taxes. Keep money in paise. Copy item names and prices into order items (see the Amazon guide).

    ✅ Check it works

    Marking an item unavailable while it is in someone's cart blocks their checkout with a clear message.

  5. Step 5

    Enforce the order state machine

    Goal: Only valid transitions by the right role are possible, even with two clicks at once.

    Write the transitions as data: from-state, to-state, and which role may do it. A single transition(orderId, to, actor) function checks the table, then updates with a condition on the current state: UPDATE orders SET status = $to WHERE id = $id AND status = $from. If 0 rows changed, someone else already moved it.

    Record every change in order_events (order, from, to, actor, time). The customer's tracking timeline and any disputes use this history.

    After each transition, emit the new status to the order's Socket.IO room so all three apps update instantly.

    src/lib/orders/state-machine.ts
    type Status = 'PLACED' | 'ACCEPTED' | 'PREPARING' | 'READY' | 'PICKED_UP' | 'DELIVERED' | 'CANCELLED'
    type Role = 'CUSTOMER' | 'RESTAURANT' | 'PARTNER' | 'SYSTEM'
    
    const ALLOWED: Record<string, Role[]> = {
      'PLACED>ACCEPTED': ['RESTAURANT'],
      'PLACED>CANCELLED': ['CUSTOMER', 'RESTAURANT', 'SYSTEM'],
      'ACCEPTED>PREPARING': ['RESTAURANT'],
      'ACCEPTED>CANCELLED': ['RESTAURANT', 'SYSTEM'],
      'PREPARING>READY': ['RESTAURANT'],
      'READY>PICKED_UP': ['PARTNER'],
      'PICKED_UP>DELIVERED': ['PARTNER'],
    }
    
    export async function transition(orderId: string, from: Status, to: Status, actor: { role: Role; id: string }) {
      if (!ALLOWED[from + '>' + to]?.includes(actor.role)) throw new Error('Not allowed')
      const res = await pool.query('UPDATE orders SET status = $3, updated_at = now() WHERE id = $1 AND status = $2', [orderId, from, to])
      if (res.rowCount === 0) throw new Error('Order already moved on')
      await pool.query('INSERT INTO order_events (order_id, from_status, to_status, actor_role, actor_id) VALUES ($1, $2, $3, $4, $5)',
        [orderId, from, to, actor.role, actor.id])
      io.to('order:' + orderId).emit('status', { orderId, status: to })
    }

    ✅ Check it works

    Clicking “Accept” in two restaurant tabs at once: one succeeds, the other shows “already moved on”. The customer cannot mark an order delivered.

    ⚠️ Common mistakes

    • Also check ownership: the restaurant must own this order and the partner must be the assigned partner. The role alone is not enough.
  6. Step 6

    Restaurant panel with live order alerts

    Goal: Restaurants hear and see new orders instantly and must respond within 3 minutes.

    The panel joins room restaurant:<id>. A new order plays a sound and shows a card with items and a 3-minute countdown. Browsers only allow sound after a user interaction, so add a “Start shift” button.

    A scheduled job cancels PLACED orders older than 3 minutes (role SYSTEM) and refunds in test mode, so customers are not left waiting.

    Columns: New, Preparing, Ready. Each card has one main button for the next state.

    ✅ Check it works

    An order placed from a phone rings the panel on a laptop within a second; ignoring it auto-cancels after 3 minutes.

  7. Step 7

    Assign the nearest free delivery partner

    Goal: When food is accepted, the closest available partner gets the task, and two orders can never claim the same partner.

    Online partners send their location (next step); keep the latest in a partners table with available and location. When an order is ACCEPTED, find available partners within 3 km of the restaurant, nearest first.

    Offer the task to the nearest partner for 30 seconds. If they decline or time out, offer it to the next one.

    Claim atomically: UPDATE partners SET available = false, current_order = $order WHERE id = $partner AND available RETURNING id. If it returns no row, another order took them first; try the next partner.

    assign partner
    -- candidates near the restaurant
    SELECT p.id, round(ST_Distance(p.location, r.location)) AS metres
    FROM partners p, restaurants r
    WHERE r.id = $1 AND p.available AND p.online
      AND ST_DWithin(p.location, r.location, 3000)
    ORDER BY metres
    LIMIT 5;
    
    -- claim one (only succeeds if still free)
    UPDATE partners SET available = false, current_order = $2
    WHERE id = $1 AND available
    RETURNING id;

    ✅ Check it works

    Two orders accepted at the same moment with one partner nearby: one gets the partner, the other moves on to the next.

  8. Step 8

    Live tracking on a map

    Goal: The customer watches the partner's bike move on the map, updated every 5 seconds.

    In the partner app, navigator.geolocation.watchPosition gives new coordinates as the phone moves. Send at most one update every 5 seconds over Socket.IO. Location only works on HTTPS pages.

    The server checks the sender is the assigned partner, saves the point (latest position in Redis or the partners table) and emits it to order:<id>. Only share location while the order is PICKED_UP or on the way to the restaurant; stop when delivered. Mention this privacy rule in your README.

    The customer map uses Leaflet with OpenStreetMap tiles (show their attribution). Move the marker smoothly between points with a short CSS transition, and update the ETA from the remaining distance.

    partner app: sending location
    let lastSent = 0
    const watchId = navigator.geolocation.watchPosition(
      (pos) => {
        const now = Date.now()
        if (now - lastSent < 5000) return
        lastSent = now
        socket.emit('partner:location', {
          orderId, lat: pos.coords.latitude, lng: pos.coords.longitude, accuracy: pos.coords.accuracy,
        })
      },
      (err) => showError('Turn on location to deliver: ' + err.message),
      { enableHighAccuracy: true, maximumAge: 5000, timeout: 20000 },
    )
    // when delivered: navigator.geolocation.clearWatch(watchId)

    ✅ Check it works

    Walk around the block with the partner phone: the customer's map shows the marker following you.

  9. Step 9

    Payments, ratings and support

    Goal: Pay online in test mode or cash on delivery, rate the food and delivery, and report problems.

    Online payment uses Razorpay test mode with server-side signature verification (see the Amazon guide). Cash on delivery skips payment and the partner marks “Cash collected”.

    After delivery, ask two ratings: food (for the restaurant) and delivery (for the partner). Keep average ratings as sum and count on each.

    A “Help” button on the order lets customers report missing items with a photo; create a support ticket and refund in test mode if approved.

    ✅ Check it works

    A test card payment marks the order paid only after the server verifies it; a COD order completes without payment.

  10. Step 10

    Demo with three phones and deploy

    Goal: A live app and a video of a full order from three devices.

    Deploy with HTTPS (required for location), PostgreSQL with PostGIS, and the Socket.IO server with WebSocket support in Nginx.

    Seed 10 restaurants around your college with real coordinates and your own dish photos. Make three demo logins: customer, restaurant, partner.

    Record a 3-minute video: order on phone 1, accept on laptop (restaurant), pick up and walk on phone 2 (partner), live map on phone 1. README: state diagram, PostGIS queries, assignment claim, privacy rules, the not-affiliated note.

    ✅ Check it works

    Someone else can repeat the whole flow using your demo logins.

🚀 Make it stand out

  • +Batching: one partner carries two orders from the same restaurant
  • +Promo codes and free-delivery rules
  • +Restaurant analytics: busiest hours and top dishes
  • +Push notifications for every status change