Stream live updates with server-sent events and WebSockets

8 steps · about 2 h 8 min · Intermediate

  1. When a one-way stream is enough (reference, MDN Web Docs, 8 min)

    Most live dashboards and notifications only push from server to browser; start with the simpler tool.

  2. Build a server-sent event stream (tutorial, MDN Web Docs, 25 min)

    Write the event-stream response format and a browser listener for named events.

  3. Handle errors and state on EventSource (reference, MDN Web Docs, 10 min)

    Read the connection states and error event so your interface can show when updates have paused.

  4. Reconnection, retry and Last-Event-ID (reference, WHATWG HTML Standard, 20 min)

    Read the processing rules that let a client resume after a dropped connection without losing or repeating events.

  5. When you need two-way messaging (reference, MDN Web Docs, 10 min)

    Chat, collaboration and games need the client to send often too; see what the WebSocket API offers and its limits.

  6. Write a WebSocket client (tutorial, MDN Web Docs, 25 min)

    Open a socket, send and parse JSON messages, and close it deliberately.

  7. Read close codes and reconnect sensibly (reference, MDN Web Docs, 10 min)

    Use the close code and reason to decide whether to retry with backoff or tell the user something is wrong.

  8. Secure a WebSocket endpoint (guide, OWASP Cheat Sheet Series, 20 min)

    Check the Origin header, authenticate the connection, validate every message and limit message size and rate.