Skip to content
YouTurkey Tech
All web topics

Live updates: SSE and WebSockets

Intermediate

How a server sends news the moment it happens: polling, a stream of Server-Sent Events, and a WebSocket that talks both ways after one HTTP request.Builds on HTTP requests and responses

GET /scores HTTP/1.1Host: live.exampleAccept: text/event-stream HTTP/1.1 200 OKContent-Type: text/event-stream data: {"home":1,"away":0} GET /chat HTTP/1.1Host: live.exampleUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Sec-WebSocket-Version: 13 HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Messages

Empty

0/14Press Play, or step through with the arrows, to begin.
Step 0 of 14

Explanation

3 min read

On this page

How can a server send updates to the browser?

In HTTP the browser asks and the server answers; a server cannot start a conversation. For live scores, chats, notifications or a shared document, the page needs news the moment it happens. There are three common ways to get it:

  1. Polling. Ask again every few seconds. Simple, but most answers say "nothing new", and news waits until the next question.
  2. Server-Sent Events (SSE). One request whose response never finishes: the server writes an event into it whenever there is news. The page reads them with EventSource.
  3. WebSockets. One request that upgrades the connection into a two-way channel, where both sides send small whenever they like. The page uses WebSocket.

How do SSE and WebSockets work underneath?

  • SSE is plain HTTP. The response has Content-Type: text/event-stream, and each event is a few field: value lines (data:, id:, event:) ended by a blank line. If the connection drops, EventSource reconnects by itself and sends Last-Event-ID, so the server can resume.
  • A WebSocket starts as HTTP. The GET carries Upgrade: websocket and a random Sec-WebSocket-Key. The server answers 101 Switching Protocols with Sec-WebSocket-Accept, a hash of that key, and from then on the connection carries WebSocket frames, not HTTP.
  • Frames are small. A text message costs only a few bytes of framing, with no headers or cookies repeated on every message. Ping and pong frames keep an idle connection alive, and a close frame ends it cleanly.
  • Choosing. Use SSE when only the server talks, such as scores, notifications or a progress bar: it works with ordinary HTTP servers and reconnects by itself. Use a WebSocket when the browser sends often too, such as chats, games or collaborative editing.

What do people get wrong about live updates?

Mini example

A stream can name its events and number them. The page listens with source.addEventListener('goal', …), and after a reconnect the browser sends the last id it saw:

GET /scores HTTP/1.1Host: live.exampleAccept: text/event-streamLast-Event-ID: 2 HTTP/1.1 200 OKContent-Type: text/event-stream id: 3event: goaldata: {"home":2,"away":1,"minute":78} 

Quick check

A dashboard only needs to show new orders as they arrive. Which fits best?

Further reading

All steps as text
  1. Step 1:

    A live score page wants to show a goal the moment it happens. In HTTP the server can only answer, so the simplest trick is polling: ask again every few seconds.

  2. Step 2:

    Most of those answers say nothing new, and a goal can wait seconds to show. With Server-Sent Events, the page opens one request instead and asks for a stream.

    Lines 1–3

  3. Step 3:

    The server answers with text/event-stream and then simply doesn’t finish the response. The connection stays open, waiting for news.

    Lines 5–6

  4. Step 4:

    Goal! The server writes an event into the open response: a data: line and a blank line. The page’s EventSource fires at once.

    Line 8

  5. Step 5:

    More events follow on the same response. Each can carry an id; if the connection drops, the browser reconnects by itself and says where it stopped.

  6. Step 6:

    SSE only goes from server to browser. A chat needs both ways, so it opens a WebSocket, which starts as an ordinary GET asking to Upgrade.

    Lines 10–15

  7. Step 7:

    The random key lets the browser check that it is talking to a real WebSocket server. CORS doesn’t cover WebSockets, so the server must check Origin itself.

    Line 14

  8. Step 8:

    101 Switching Protocols: the accept value is a hash of the key, and from now on this connection no longer speaks HTTP. Both sides can send whenever they like.

    Lines 17–20

  9. Step 9:

    Sara types “Hi all” and the page calls socket.send(). It travels as a small frame: no request line, no headers, just a few bytes around the text.

  10. Step 10:

    Another visitor has a WebSocket open to the same server. The server pushes Sara’s message to them right away, without being asked.

  11. Step 11:

    They reply, and the server passes it on to Sara. Messages go both ways on the same connections, at any moment.

  12. Step 12:

    When the chat is quiet, the server sends a ping and the browser answers pong by itself. That keeps routers and proxies from dropping an idle connection.

  13. Step 13:

    Sara closes the tab. The browser sends a close frame, the server answers with one, and the connection ends cleanly.

  14. Step 14:

    Polling asks again and again, SSE keeps one HTTP response open for news from the server, and a WebSocket turns one request into a two-way channel.