Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 87 ยท Data Fetching

Real-Time Vue: WebSockets and Server-Sent Events

Build real-time Vue 3 features: a useWebSocket composable with status, reconnect and cleanup, a useEventSource composable, and how to choose between WebSockets, SSE and polling.

Fetching data is a question followed by an answer. Many features work the other way round: a chat message arrives, a price changes, a build finishes, and the server wants to tell the page. For that you need a connection that stays open. The browser has two built-in tools: WebSocket (two-way) and Server-Sent Events, SSE (server to browser only, through EventSource).

Both give you the same problems to solve in a Vue app: show the connection status, parse messages into reactive state, send messages safely, reconnect when the network drops, and close the connection when the component goes away. A composable is the right home for all of that, so the component only sees refs.

Choosing the tool

WebSocket Server-Sent Events Polling (fetch on a timer)
Direction Both ways Server to browser Browser asks, server answers
Protocol Its own (ws://, wss://) Plain HTTP, text/event-stream Plain HTTP
Reconnects by itself No, you write it Yes, built in (with Last-Event-ID) Not needed
Binary data Yes No (text only) Yes
Good for Chat, games, collaboration Live feeds, notifications, progress Simple, infrequent updates

If the data only flows from server to page, SSE is the simplest choice. Use WebSocket when the page also sends frequent messages. Use polling when updates are rare and you want the easiest infrastructure.

A sandbox note: fake sockets

The preview on this site cannot open a real connection, so the examples use FakeSocket and FakeEventSource, small classes that copy the browser API (onopen, onmessage, onclose, send, close, readyState) and produce messages with timers. The composables take a createSocket function, so in production you pass nothing and they use the real WebSocket. Accepting the dependency as an argument also makes the composable easy to test.

A useWebSocket composable

The composable owns four things: the connection, a status ref, a messages ref and the reconnect logic. Reconnecting uses exponential backoff: wait 0.4 s, then 0.8 s, 1.6 s and so on, up to a limit, so a server that is down is not hammered by thousands of clients at once.

useWebSocket with status, send and automatic reconnect

Send a message and the echo comes back. Press Simulate server drop: the status goes to waiting, the composable schedules a reconnect with a growing delay, and a moment later the status is open again and the attempt counter resets. Nothing in the template knows how reconnecting works.

A few design points worth copying:

  • closedByUs separates deliberate from accidental closing. Without it, closing on unmount would trigger a reconnect.
  • send returns a boolean instead of throwing when the socket is not open, so the UI can react (disable the button, queue the message).
  • onScopeDispose(close) guarantees cleanup in components and in any other effect scope (composable patterns). A connection left open after the page changes keeps receiving messages and leaks memory.
  • Messages are parsed once, in onmessage. Parse inside a try/catch in production, because a server can send a malformed frame.

What the real server needs from you

With a real WebSocket, a few extra rules apply. Use wss:// (encrypted) on any public site. Authenticate the connection: browsers cannot set custom headers on a WebSocket, so send a short-lived token in the first message or in the URL's query string, and have the server validate it (auth patterns). Add a heartbeat (ping/pong) if proxies in front of your server close idle connections. Cap the length of the messages array, as the example does when it renders, because a busy feed grows without limit.

Server-Sent Events with useEventSource

EventSource is simpler than WebSocket because the browser reconnects for you and remembers the last event id. The server answers a normal GET request with Content-Type: text/event-stream and writes lines such as event: price and data: {"symbol":"VUE","price":42}. In the browser you listen either to the default message event or to named events with addEventListener.

useEventSource with a named event (fake stream)

Prices appear row by row as events arrive, and the colour shows whether the last change went up or down. A named event keeps the stream tidy: one connection can carry price, news and alert events, each with its own listener. Disconnect calls close(), which is what you must also do on unmount, and Connect opens a fresh stream.

Two limits of SSE are worth knowing: browsers allow only a handful of open connections per host over HTTP/1.1 (HTTP/2 lifts that), and EventSource cannot send custom headers, so token authentication needs a cookie or a query parameter. If you need those, either use WebSocket or a fetch-based stream reader.

Putting real-time data in a store

If several components need the same live data, do not open one connection per component. Open it once in a Pinia store or a module-level singleton, and let components read its state. The store's connect() action runs when the app starts (or when the user signs in), and disconnect() runs when the user signs out.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which tool fits a live feed where the page never sends data back, and where you want built-in reconnection?

    SSE is one-directional (server to browser) and EventSource reconnects automatically. WebSocket is the better choice when the page also sends frequent messages.
  2. 2. Why does useWebSocket keep a closedByUs flag?

    The close event looks the same whether the server dropped the connection or you closed it. The flag tells the handler which case it is.
  3. 3. What is exponential backoff?

    Growing delays avoid flooding a struggling server with reconnect requests from every client at the same moment.
  4. 4. Where should the connection be closed when it belongs to a component?

    An open connection outlives the component and keeps delivering messages to state nobody shows. Register cleanup with onScopeDispose so it runs on unmount.

Summary

  • WebSocket is two-way; SSE is server-to-browser with automatic reconnection; polling is the simplest for rare updates.
  • Wrap a connection in a composable that returns status, data refs and actions, and takes a socket factory so it can be tested.
  • Reconnect with exponential backoff, and distinguish a deliberate close from a drop.
  • Always close the connection with onScopeDispose or onUnmounted.
  • Authenticate real connections, use wss://, and share one live connection through a store instead of opening many.

Next: services that give you auth, a database and live updates without writing a server, Vue with Firebase, Supabase and GraphQL.