Under The Hood
frontend htmx HTMX 1.x / 2.x (ext/sse.js, ext/ws.js)

Server-Sent Events (SSE) & WebSockets Extensions for Real-Time DOM Morphing

Last updated
Prerequisites:
Server-Sent Events (`EventSource`)
WebSocket protocol basics
  • htmx
  • sse
  • websockets
  • real-time
  • streaming
  • extensions

Read at your depth

The practical view

HTMX supports real-time updates via official extensions: `sse.js` and `ws.js`. For Server-Sent Events: `<div hx-ext="sse" sse-connect="/events" sse-swap="message">`. The element connects to the SSE stream and swaps incoming HTML payloads directly into the DOM. For WebSockets: `<div hx-ext="ws" ws-connect="/chat">` allows both receiving HTML pushes and sending form payloads over the WebSocket connection (`ws-send`).

The same idea in other frameworks

react equivalent
Socket.io / standard WebSocket hook updating React state arrays.

Legacy vs modern

Manual WebSocket JSON Listener vs Declarative HTMX WS Extension

Manual WebSockets require state parsing and element creation; HTMX WS extensions swap streamed HTML directly into the target.

before → after
Manual WebSocket JSON Client
ws.onmessage = (e) => { const { msg } = JSON.parse(e.data); append(msg); }; // ❌ Client template plumbing
Declarative HTMX SSE Stream
<div hx-ext="sse" sse-connect="/chat-feed" sse-swap="new_message" hx-swap="beforeend"> // ✅ NEW

Interview gotchas

Context

Interviewers test your knowledge of the SSE wire protocol and HTMX integration.

The mechanical answer

The server must format responses according to the W3C SSE standard with an event name and HTML data string. For example: ```http event: new_message data: <div class="chat-bubble">Hello World!</div> ``` The `event:` name matches `sse-swap="new_message"`, and the `data:` contains the raw HTML fragment to swap.

Trap

SSE messages require two trailing newline characters (`\n\n`) to flush the event over the HTTP stream.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.