Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 87 ยท Projects

Project: Chat App

Build a chat app in Vue 3: optimistic sending with sent and failed states, a retry button, auto-scrolling that respects the reader, then a WebSocket composable with acknowledgements and reconnect.

Chat looks like a simple list with a text box, but it is one of the best projects for learning how real-time interfaces feel. When you press Enter, your message must appear instantly, even though the server has not answered yet. If sending fails, the message must say so and offer a retry. New messages must scroll into view, but only if you are not reading older ones. And if the connection drops, the app must notice, reconnect and not lose your work.

We build it in two stages. Stage 1 uses a mock request and focuses on the optimistic UI and the scroll behaviour. Stage 2 swaps in a live connection with a composable, acknowledgements and reconnecting. Background lessons: real-time Vue, watch, template refs, next tick and lifecycle hooks.

Design first

A message is { id, text, mine, status }. The interesting field is status, which for your own messages moves through a tiny state machine:

stateDiagram-v2
    [*] --> sending: you press Enter
    sending --> sent: server confirms
    sending --> failed: error or connection lost
    failed --> sending: Retry

The message is on screen from the first moment. Only its status changes.

This is optimistic UI: assume success, show the result immediately and correct it if reality disagrees. It makes apps feel fast, and it is safe when the failure case is handled visibly. The rule that makes it work is that every message gets a client-made id before it is sent, so the confirmation or error can be matched to the right message later.

Scrolling needs a rule, too. When a message arrives:

  • if you sent it, or you were already at the bottom, scroll down to show it;
  • if you scrolled up to read history, do not yank you away. Show a "new messages" button instead.

The key to the second rule is measuring "were we at the bottom?" before Vue updates the DOM, because after the update the new message has made the list taller. A watch with flush: "pre" runs before the DOM update, and nextTick waits for it to finish.

Stage 1: optimistic sending and smart scrolling

The mock postMessage takes 600 ms and fails if the text contains the word fail, so you can test the failed state and the retry. A bot answers after each successful message.

Stage 1: optimistic messages, retry and auto-scroll

Send "hello": your bubble appears at once saying sending..., then sent after 600 ms, and the bot answers. Send "this will fail": it turns red with a retry link. Fill the list, scroll up and send again: your own message always scrolls into view, but the bot's reply only raises the new message pill while you are reading older ones.

Study the details:

  1. Push first, deliver second. The message exists before the request starts. deliver receives the reactive object, read back with find, so assigning message.status triggers a re-render. (Mutating the plain object that was pushed would not: messages.value.push(obj) stores a proxy of it, and only writes through the proxy are tracked. See reactivity pitfalls.)
  2. flush: "pre" plus nextTick. Measuring before the update is what makes "was the reader at the bottom?" correct. If you measured after the update, a long message would push the bottom away and you would never scroll.
  3. Failure is visible and recoverable. A failed message stays in the list, in a different colour, with a retry action. Never silently drop a user's text.
  4. retry reuses deliver. Same function, same path.

The weakness: everything here is a pretend server call, and there is no notion of a connection that can be lost. Next, a live socket.

Stage 2: a connection composable with acknowledgements and reconnect

With a WebSocket there are two new facts of life. A send does not prove delivery, so the server must send back an acknowledgement carrying the client id (ack) or an error (error). And the connection can drop, so messages that were sending at that moment must become failed, and the app must reconnect and tell the user.

The composable useChat contains all of that. The component only sees messages, status and the actions send and retry. The sandbox cannot open a real socket, so FakeSocket imitates a chat server: it acknowledges each message, rejects texts containing "fail", answers like a bot, and can be dropped with a button. With a real server you would pass () => new WebSocket("wss://...") instead (real-time Vue explains the details and backoff).

Stage 2: useChat with acks, failures and reconnect

Wait for open, send "hello" and watch the bubble go from sending to sent, followed by the bot's reversed reply. Send "fail" for a server-side error. Now send a message and press Simulate connection loss at once: the status changes to reconnecting, the unconfirmed message turns failed, and the Send button is disabled until the status is open again. After reconnecting, press retry on the failed message.

What the design gets right:

  • The composable is the only place that knows about sockets. The component works with messages, status, send and retry. Replacing the fake with a real WebSocket, or with Server-Sent Events plus fetch for sending, touches only useChat.
  • Acks make statuses honest. sent means "the server confirmed", not "we wrote bytes".
  • Pending messages fail on disconnect. We cannot know whether the server received them, so we say failed and let the user retry. A production app may add a unique client id the server uses to ignore duplicates (idempotency), so a retry can never post twice.
  • The send button follows the connection. :disabled="status !== 'open'" stops people typing into a void. Another option is to queue messages while offline and flush them on reconnect.
  • Cleanup is automatic. onScopeDispose(close) closes the socket and cancels a pending reconnect when the component goes away.

Where to go next

  • Add usernames and avatars, grouping consecutive messages from the same person.
  • Show "someone is typing" with a throttled typing event, and hide it after a few seconds of silence.
  • Load older history when you scroll to the top. Remember to preserve the scroll position after prepending items (measure scrollHeight before and after).
  • Put the connection in a store so several components (a sidebar with unread counts, the chat window) share one socket.
  • Add rooms, and authenticate the connection (auth patterns). Never trust the mine flag from the client: the server must decide who sent a message.
  • Escape or sanitize text. Vue's {{ }} escapes it, which is exactly why you should never render chat with v-html (Vue security).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is an optimistic UI update?

    The interface assumes success so it feels instant, but it must still handle failure visibly, for example with a failed state and a retry action.
  2. 2. Why does every message get a client-made id before it is sent?

    Responses arrive later and possibly out of order. The client id is the key that links the response to the message on screen.
  3. 3. Why is the scroll watcher declared with flush: "pre"?

    After the DOM update the list is taller, so the bottom check would fail. With flush pre, the callback sees the old layout and then waits for nextTick before scrolling.
  4. 4. What should happen to messages that are 'sending' when the connection closes?

    Honesty beats guessing. The user decides whether to retry, and the server can ignore duplicates by client id.
  5. 5. Why should chat text be rendered with {{ }} and not v-html?

    Messages come from other users. Rendering them as HTML would let attackers inject scripts.

Summary

  • Optimistic UI: show the message immediately with a sending status, then move it to sent or failed, and always offer a retry.
  • Give each message a client-made id so acknowledgements and errors can be matched.
  • Scroll to the newest message only when the reader is at the bottom (or sent it); otherwise show a "new messages" button. Measure with a flush: "pre" watcher, then wait for nextTick.
  • Put the socket, acks and reconnect logic in one composable and close it with onScopeDispose.
  • On disconnect, mark unconfirmed messages as failed and disable sending until the connection is open.
  • Render chat text with {{ }}, never v-html.

Next: shopping features at full size, Project: Storefront with Pinia and Router.