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

WhatsApp clone: chat app with ticks, groups and media

One-to-one and group chat with single, double and blue ticks, typing indicators, online / last seen, unread counts, image messages and reliable delivery when the network drops.

Advanced⏱ 30–40 hours★ 10 detailed steps with codeNode.jsSocket.IOPostgreSQLPrismaRedisReact

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

What you’ll learn

  • ◆Reliable messaging: client ids, acknowledgements and retries
  • ◆Delivered and read receipts that scale (pointers, not per-message rows)
  • ◆Presence with Redis across several devices
  • ◆Syncing missed messages after going offline

What you’ll build

  • ✓Email OTP login and contacts by username
  • ✓1:1 and group chats with admins
  • ✓✓ sent, ✓✓ delivered, blue ✓✓ read
  • ✓Typing…, online/last seen, unread badges, images

Before you start

What you need

  • •React, Node.js and SQL basics; the “Real-time chat app (Socket.IO)” guide on this page is a good warm-up.
  • •Node.js 20+, PostgreSQL and Redis (Docker is easiest).
  • •An email sending method for OTPs (any SMTP; use a test SMTP like Ethereal while developing).

How it fits together

  1. 1React client ⇄ Socket.IO server (Node) for live events; REST endpoints for history and uploads.
  2. 2PostgreSQL stores conversations, members and messages. Each member row stores “delivered up to” and “read up to” times, which give the ticks.
  3. 3Every user's sockets join a room user:<id>, so a message reaches all their devices.
  4. 4Redis tracks how many sockets each user has open (online / last seen) and lets several servers share rooms.

Project structure

folders
chatly/
├─ prisma/schema.prisma
├─ server/
│  ├─ index.ts          # Express + Socket.IO + Redis adapter
│  ├─ auth.ts           # email OTP + JWT
│  ├─ messages.ts       # send, ack, receipts
│  ├─ presence.ts
│  └─ uploads.ts
└─ web/
   ├─ ChatList.tsx, ChatWindow.tsx, MessageBubble.tsx
   └─ outbox.ts         # pending messages + retry

Step-by-step guide

  1. Step 1

    Plan v1 and how ticks will work

    Goal: A feature list and a precise definition of each tick.

    v1: login by email OTP, find users by username, 1:1 chats, groups up to 50, text and image messages, ticks, typing, online/last seen, unread counts, and catching up after being offline. Later: voice notes, calls, end-to-end encryption.

    Define ticks exactly: one grey tick = the server saved it. Two grey ticks = it reached every other member's device. Two blue ticks = every other member opened the chat after it arrived. In groups, “every” means all members, so ticks turn blue only when the last person reads.

    Give it your own name and colours (“Chatly”), not WhatsApp's green logo.

    ✅ Check it works

    You can explain when a group message turns blue.

  2. Step 2

    Design the schema with read and delivery pointers

    Goal: Conversations, members and messages, where receipts cost one row per member, not per message.

    Naive receipts store a row per (message, recipient). A group of 50 sending 1,000 messages means 50,000 receipt rows. Instead, each Member row stores deliveredUpTo and readUpTo timestamps. A message is delivered to a member if member.deliveredUpTo >= message.createdAt. Updating receipts becomes one small UPDATE.

    A direct chat needs a stable key so two people never get two separate chats: sort the two user ids and join them (directKey).

    Each message has a clientId generated by the sender's app; unique per sender. If the app retries after a network drop, the server recognises the duplicate.

    prisma/schema.prisma
    model Conversation {
      id        String    @id @default(cuid())
      type      String    // DIRECT | GROUP
      directKey String?   @unique          // "userA:userB" sorted, only for DIRECT
      title     String?
      members   Member[]
      messages  Message[]
      createdAt DateTime  @default(now())
    }
    
    model Member {
      conversationId String
      userId         String
      role           String       @default("MEMBER")   // ADMIN | MEMBER
      deliveredUpTo  DateTime     @default(now())
      readUpTo       DateTime     @default(now())
      conversation   Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
      @@id([conversationId, userId])
      @@index([userId])
    }
    
    model Message {
      id             String       @id @default(cuid())
      conversationId String
      senderId       String
      clientId       String
      kind           String       @default("TEXT")   // TEXT | IMAGE | SYSTEM
      body           String
      mediaUrl       String?
      createdAt      DateTime     @default(now())
      conversation   Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
      @@unique([senderId, clientId])
      @@index([conversationId, createdAt])
    }

    ✅ Check it works

    Creating the same 1:1 chat twice (A→B and B→A) returns the same conversation.

  3. Step 3

    Login with email OTP and authenticate sockets

    Goal: Users log in with a 6-digit code and every socket connection knows who the user is.

    Send a random 6-digit code (crypto.randomInt(0, 1_000_000) padded to 6 digits), store only its hash with a 10-minute expiry, allow 5 attempts, and allow a resend only after 60 seconds. On success, issue a JWT (or a session id).

    The client passes the token when connecting: io(url, { auth: { token } }). A io.use middleware verifies it and sets socket.data.userId; unauthenticated connections are refused before any event runs.

    On connection, join user:<id>. A user with a phone and a laptop has two sockets in the same room, so emitting to the room reaches both devices.

    server/index.ts
    io.use((socket, next) => {
      try {
        const payload = jwt.verify(String(socket.handshake.auth.token), process.env.JWT_SECRET!) as { sub: string }
        socket.data.userId = payload.sub
        next()
      } catch {
        next(new Error('unauthorised'))
      }
    })
    
    io.on('connection', async (socket) => {
      const userId: string = socket.data.userId
      socket.join('user:' + userId)
      await presenceOnline(userId)           // step 8
      registerMessageHandlers(io, socket)     // steps 4-6
      socket.on('disconnect', () => presenceOffline(userId))
    })

    ✅ Check it works

    Connecting with no token or a wrong token is rejected; with a valid token, two tabs of the same user both receive a test event sent to user:<id>.

  4. Step 4

    Send messages reliably with acknowledgements

    Goal: Messages show a clock while sending, one tick when saved, and are never lost or duplicated on retry.

    The client creates a clientId (crypto.randomUUID()), shows the message immediately with a clock icon, and stores it in an “outbox”. It emits send with an acknowledgement callback. When the server answers, the clock becomes one tick.

    The server checks the sender is a member, trims the text (max 4,000 characters), and saves with upsert on (senderId, clientId). If the same message arrives twice because the client retried, the second upsert returns the existing row instead of creating a duplicate.

    Then it emits the saved message to user:<id> of every member, including the sender's other devices. If the ack does not arrive within 10 seconds, the client retries; on reconnect it resends everything still in the outbox.

    server/messages.ts
    socket.on('send', async (m: { conversationId: string; clientId: string; body: string }, ack) => {
      const me: string = socket.data.userId
      const member = await db.member.findUnique({ where: { conversationId_userId: { conversationId: m.conversationId, userId: me } } })
      if (!member) return ack({ error: 'not a member' })
      const body = String(m.body ?? '').trim().slice(0, 4000)
      if (!body) return ack({ error: 'empty' })
    
      const msg = await db.message.upsert({
        where: { senderId_clientId: { senderId: me, clientId: String(m.clientId) } },
        update: {},                                    // retry: return the saved message as it is
        create: { conversationId: m.conversationId, senderId: me, clientId: String(m.clientId), body },
      })
      ack({ id: msg.id, createdAt: msg.createdAt })
    
      const members = await db.member.findMany({ where: { conversationId: m.conversationId }, select: { userId: true } })
      for (const { userId } of members) io.to('user:' + userId).emit('message', msg)
    })

    ✅ Check it works

    Turn on DevTools “Offline”, send 3 messages (clocks), go back online: all 3 arrive once each and turn into ticks.

    ⚠️ Common mistakes

    • Making clientId globally unique instead of unique per sender: someone could send another user's clientId and get their message back.
  5. Step 5

    Delivered and read ticks

    Goal: Two grey ticks when the other side receives, blue when they read, in 1:1 and groups.

    When a client receives a message, it emits delivered with the message time. When the chat is open and the window is visible (document.visibilityState === "visible"), it emits read. The server moves the member's pointer forward only, using GREATEST, so a late, older event can never move it back.

    Then the server notifies the other members with the member's new pointers. The sender's app computes each message's ticks: blue if every other member's readUpTo >= createdAt, two grey if every other member's deliveredUpTo >= createdAt, otherwise one tick.

    Batch these events on the client: send “read up to the newest message” once, not one event per message.

    server/messages.ts (receipts)
    socket.on('read', async ({ conversationId, upTo }: { conversationId: string; upTo: string }) => {
      const me: string = socket.data.userId
      const when = new Date(upTo)
      if (Number.isNaN(when.getTime())) return
      const n = await db.$executeRawUnsafe(
        'UPDATE "Member" SET "readUpTo" = GREATEST("readUpTo", $3), "deliveredUpTo" = GREATEST("deliveredUpTo", $3) ' +
        'WHERE "conversationId" = $1 AND "userId" = $2',
        conversationId, me, when)
      if (!n) return
      const members = await db.member.findMany({ where: { conversationId } })
      for (const m of members) io.to('user:' + m.userId).emit('receipts', { conversationId, members })
    })
    
    // client: ticks for one of my messages
    export function ticks(msg: { createdAt: string; senderId: string }, members: MemberDto[]) {
      const others = members.filter((m) => m.userId !== msg.senderId)
      if (others.every((m) => m.readUpTo >= msg.createdAt)) return 'read'          // blue ✓✓
      if (others.every((m) => m.deliveredUpTo >= msg.createdAt)) return 'delivered' // grey ✓✓
      return 'sent'                                                                 // ✓
    }

    ✅ Check it works

    In a 3-person group, a message turns blue only after both other people open the chat.

  6. Step 6

    Chat list, unread counts and catching up after offline

    Goal: The chat list shows last message and unread count, and reconnecting loads everything you missed.

    The chat list is one SQL query: your memberships joined with each conversation's latest message (a LATERAL subquery) and a count of messages newer than your readUpTo that you did not send. Order by latest message time.

    Message history uses cursor pagination: “the 30 messages before this createdAt”. Offset pagination (OFFSET 300) gets slower as chats grow and skips messages when new ones arrive.

    On reconnect, for each open conversation, the client asks for messages after the newest one it has. Combined with the outbox from step 4, nothing is lost in either direction.

    chat list query
    SELECT c.id, c.type, c.title, last.body AS last_body, last."createdAt" AS last_at,
           (SELECT count(*) FROM "Message" x
             WHERE x."conversationId" = c.id AND x."createdAt" > m."readUpTo" AND x."senderId" <> $1) AS unread
    FROM "Member" m
    JOIN "Conversation" c ON c.id = m."conversationId"
    LEFT JOIN LATERAL (
      SELECT body, "createdAt" FROM "Message"
      WHERE "conversationId" = c.id ORDER BY "createdAt" DESC LIMIT 1
    ) last ON true
    WHERE m."userId" = $1
    ORDER BY last."createdAt" DESC NULLS LAST
    LIMIT 50;

    ✅ Check it works

    Close the app, receive 5 messages in 2 chats, reopen: both chats show the right unread counts and all messages load.

  7. Step 7

    Typing indicator and online / last seen

    Goal: “typing…” appears instantly, and contacts show online or “last seen today at 9:41 pm”.

    Typing is a throwaway event: the client emits typing at most once every 2 seconds while the user types; receivers show “typing…” and hide it after 3 seconds of silence. Never store typing events.

    Online status: a user can have several devices. In Redis, INCR online:<id> on connect and DECR on disconnect. They are online while the count is above 0. When it reaches 0, save lastSeen = now() in the database and tell their contacts.

    Add a privacy setting “Who can see my last seen: Everyone / My contacts / Nobody” and check it before sending presence to others.

    server/presence.ts
    export async function presenceOnline(userId: string) {
      const n = await redis.incr('online:' + userId)
      if (n === 1) notifyContacts(userId, { online: true })
    }
    
    export async function presenceOffline(userId: string) {
      const n = await redis.decr('online:' + userId)
      if (n <= 0) {
        await redis.del('online:' + userId)
        const lastSeen = new Date()
        await db.user.update({ where: { id: userId }, data: { lastSeen } })
        notifyContacts(userId, { online: false, lastSeen })
      }
    }

    ✅ Check it works

    Open on phone and laptop, close only the laptop: you stay online; close both: “last seen just now”.

  8. Step 8

    Groups with admins and system messages

    Goal: Create groups, add and remove people (admins only), with “Asha added Ravi” messages.

    Creating a group makes the creator ADMIN. Only admins can add or remove members and change the title; check the role on the server for every such action.

    Record each change as a SYSTEM message (“Asha added Ravi”, “Ravi left”). It shows in the chat, and new members see from when they joined.

    A removed member must stop receiving messages immediately: delete the Member row before emitting further messages. Because messages are sent to user:<id> rooms based on current members, no room cleanup is needed.

    ✅ Check it works

    A non-admin who calls “add member” with a crafted request gets an error; a removed member receives nothing new.

  9. Step 9

    Send images

    Goal: Users can send photos that load quickly as thumbnails and open full size.

    Upload with multer (limit 10 MB, images only), process with sharp: .rotate() fixes phone orientation, resize to 1600px and make a 320px thumbnail. Sharp drops metadata by default, which removes the GPS location hidden in many phone photos.

    Store files under a random name, then send a message with kind: "IMAGE" and the URLs, through the same reliable send path as text.

    Only members of the conversation should open the image: serve files through a route that checks membership, or use signed URLs.

    ✅ Check it works

    A phone photo sent from a laptop appears upright, as a thumbnail first, and the downloaded file has no GPS data.

  10. Step 10

    Deploy, add notifications and explain encryption

    Goal: A live app installable on phones, with an honest note on what end-to-end encryption would add.

    Deploy Node + Socket.IO behind Nginx with HTTPS and WebSocket upgrade headers, PostgreSQL and Redis. Add the Socket.IO Redis adapter so you can run 2 processes.

    Make the React app a PWA (manifest + service worker) and add Web Push notifications for messages when the app is closed.

    In the README, be honest: messages are encrypted in transit (HTTPS/WSS) but the server can read them. Real WhatsApp uses the Signal protocol so only devices can decrypt. As an extension, demo 1:1 end-to-end encryption with libsodium crypto_box. Add “Educational project inspired by WhatsApp. Not affiliated.”

    ✅ Check it works

    Two friends on different networks can chat, see correct ticks, go offline and catch up.

🚀 Make it stand out

  • +Voice notes with MediaRecorder
  • +Reply, react with emoji, delete for everyone (within 1 hour)
  • +End-to-end encryption demo with libsodium
  • +Message search inside a chat