SSE and WebSocket — HTMX

SSE (Server-Sent Events) is one one-way connection, from the server to the browser, with event:, data: and id: messages separated by blank lines. WebSocket is…

Mrs. Rini's order board is up on the shop's TV, and it uses hx-trigger="every 30s". Mrs. Rini changes #12 to Ironing, but the TV only follows 26 seconds later. The customer waiting in front of it has already gone to ask the cashier.

Polling asks again and again, "anything new?". SSE (Server-Sent Events) turns that around: the browser opens one connection that stays open, and the server pushes news through it the moment something changes. WebSocket is one open connection too, but two-way: the browser and the server can both send at any time. Mrs. Rini's Laundry customers come in the same three kinds. Polling is the customer who phones every 30 minutes, "is my laundry done?". SSE is the customer subscribed to Mrs. Rini's messages, which arrive right when the status changes. WebSocket is a phone call left connected, where both sides can talk.

An SSE stream: one connection, many messages

The browser asks for GET /board/stream and the server replies with Content-Type: text/event-stream without closing the connection. Every time something changes, the server writes one message:

id: 1
event: order-12
data: <li id="order-12" sse-swap="order-12" hx-swap="outerHTML">#12 Mr. Darto, 3 kg: <span>Ironing</span></li>

id: 2
event: newOrder
data: <li id="order-15" sse-swap="order-15" hx-swap="outerHTML">#15 Mrs. Tini, 4 kg: <span>Queued</span></li>

The sse extension: sse-connect and sse-swap

<script src="https://unpkg.com/[email protected]"></script>

<div hx-ext="sse" sse-connect="/board/stream">
  <ul id="order-board" sse-swap="newOrder" hx-swap="beforeend">
    <li id="order-12" sse-swap="order-12" hx-swap="outerHTML">#12 Mr. Darto, 3 kg: <span>Washing</span></li>
    <li id="order-13" sse-swap="order-13" hx-swap="outerHTML">#13 Ms. Wulan, 2 kg: <span>Ironing</span></li>
  </ul>
  <span hx-get="/count" hx-trigger="sse:newOrder">3 orders today</span>
</div>

In Laravel 13, response()->eventStream() writes that format for you:

use Illuminate\Http\StreamedEvent;
use Illuminate\Support\Str;

Route::get('/board/stream', function () {
    return response()->eventStream(function () {
        $since = now();
        $until = now()->addMinutes(5);
        $round = 0;
        while (now()->isBefore($until)) {
            $checked = now();
            foreach (Order::where('updated_at', '>', $since)->get() as $order) {
                $row = view('board._row', ['order' => $order])->render();
                yield new StreamedEvent(event: "order-{$order->id}", data: Str::squish($row));
            }
            $since = $checked;
            if (++$round % 15 === 0) {
                yield new StreamedEvent(event: 'ping', data: 'ping'); // no element catches it
            }
            sleep(1);
        }
    });
});

Str::squish() flattens the HTML onto one line. A value yielded without StreamedEvent is named update, not message.

The two additions to the loop protect the PHP worker. PHP only notices a closed tab when it writes to the connection, and eventStream() checks connection_aborted() only when a message is yielded. Without a ping every 15 seconds, a board with no new orders keeps its worker for good, even after the TV is switched off. After 5 minutes the loop ends, and EventSource reconnects by itself a few seconds later.

Polling or SSE: when the news arrives

every 30s SSE
#12 changes at 08:00:04, shows on the board 08:00:30, 26 seconds late 08:00:04, at once
Requests per hour, one tab 120, mostly with the same content 1 connection that stays open

The board was opened at 08:00:00, so polling asks at 08:00:30, 08:01:00 and so on. The change to #12 at 08:00:04 only shows at 08:00:30, on its next turn to ask. SSE shows it right then.

When the connection drops

WebSocket: two-way

<script src="https://unpkg.com/[email protected]"></script>

<div hx-ext="ws" ws-connect="/board/ws">
  <ul id="messages"></ul>
  <form ws-send>
    <input name="message" placeholder="Message to the courier">
    <button>Send</button>
  </form>
</div>

When polling is enough

⚠️ Connections that never open, and messages nobody catches

TL;DR: SSE (Server-Sent Events) is one one-way connection, from the server to the browser, with event:, data: and id: messages separated by blank lines. WebSocket is two-way. With the sse extension: hx-ext="sse" and sse-connect="/board/stream" on the wrapper, sse-swap="order-12" (or message for unnamed messages) on the receiving element, hx-trigger="sse:newOrder" to trigger a request, and sse-close to close. A short drop: the browser reconnects and sends Last-Event-ID. The browser gives up: the extension tries again with delays of 0.5, 1, 2, 4 seconds up to 64 seconds. With the ws extension: ws-connect, HTML messages swapped by id, and ws-send sending a form as JSON. every 30s can be up to 30 seconds late, SSE is immediate. Polling is enough when lateness doesn't matter, and remember SSE holds one PHP worker per tab.

⚡ Polling or SSE

Guess first: the board uses every 30s and was opened at 08:00:00. Order #12's status changes at 08:00:04. When does the change show?

At 08:00:30, 26 seconds late, on its next turn to ask. With SSE, the change shows right away, at 08:00:04.

Meaning: SSE is one one-way connection that stays open: the server pushes news through it the moment something changes. WebSocket is one open connection too, but two-way.

⚡ sse-connect and sse-swap

Write:

<script src="https://unpkg.com/[email protected]"></script>

<div hx-ext="sse" sse-connect="/board/stream">
  <ul id="order-board" sse-swap="newOrder" hx-swap="beforeend">
    <li id="order-12" sse-swap="order-12" hx-swap="outerHTML">#12 Mr. Darto, 3 kg: <span>Washing</span></li>
    <li id="order-13" sse-swap="order-13" hx-swap="outerHTML">#13 Ms. Wulan, 2 kg: <span>Ironing</span></li>
  </ul>
  <span hx-get="/count" hx-trigger="sse:newOrder">3 orders today</span>
</div>

Meaning: sse-connect on the wrapper opens one connection for everything inside it. sse-swap="order-12" swaps the content of a message named order-12 into that element. A message with no event: line is named message.

⚡ Sometimes polling is enough

Meaning: Polling fits when being a few seconds late is fine, and it runs on any hosting. Count the cost too: in Laravel on PHP-FPM, every open SSE connection holds one PHP worker.

What you will learn