Debian Codegraph @

www/src/content/extensions/02-hx-sse.md

raw symbols SCIP
1 ---
2 title: "hx-sse"
3 description: "Stream updates via Server-Sent Events (SSE)"
4 category: "Networking"
5 icon: "icon-[mdi--rss]"
6 keywords: ["sse", "server-sent events", "event stream", "streaming", "real-time"]
7 ---
8
9 The SSE extension adds support for [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) streaming to htmx. It works by intercepting any htmx response with `Content-Type: text/event-stream` and streaming SSE messages into the DOM in real-time.
10
11 SSE is a lightweight alternative to WebSockets that works over existing HTTP connections, making it easy to use through proxy servers and firewalls. SSE is uni-directional: the server pushes data to the client. If you need bi-directional communication, consider [WebSockets](/extensions/hx-ws) instead.
12
13 ## Installing
14
15 ```html
16 <script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/htmx.min.js"></script>
17 <script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/ext/hx-sse.js"></script>
18 ```
19
20 ## How It Works
21
22 The SSE extension hooks into htmx's request pipeline. When any htmx request receives a response with `Content-Type: text/event-stream`, the extension takes over and streams SSE messages into the DOM instead of performing a normal swap.
23
24 This means **any [`hx-get`](/reference/attributes/hx-get), [`hx-post`](/reference/attributes/hx-post), etc. that returns an SSE stream will just work**, no special attributes needed beyond loading the extension.
25
26 ## `hx-sse:connect`
27
28 For persistent SSE connections (auto-connect on load, reconnect on failure), use `hx-sse:connect`:
29
30 ```html
31 <!-- Auto-connects on load, streams messages into the div -->
32 <div hx-sse:connect="/stream">
33 Waiting for messages...
34 </div>
35 ```
36
37 `hx-sse:connect` is convenience sugar for a well-preconfigured `hx-get`. It defaults to:
38 - **Trigger**: `load` (connects immediately)
39 - **Reconnect**: enabled with exponential backoff
40 - **Pause on background**: closes the stream when the tab is backgrounded, reconnects when visible
41
42 ### Using with Standard Attributes
43
44 `hx-sse:connect` works with all standard htmx attributes:
45
46 ```html
47 <!-- Swap into a different target -->
48 <button hx-sse:connect="/notifications" hx-target="#alerts">
49 Start Notifications
50 </button>
51 <div id="alerts"></div>
52
53 <!-- Append messages instead of replacing -->
54 <div hx-sse:connect="/log" hx-swap="beforeend">
55 <h3>Log:</h3>
56 </div>
57 ```
58
59 ### Trigger Modifiers
60
61 All standard [`hx-trigger`](/reference/attributes/hx-trigger) modifiers are supported:
62
63 ```html
64 <!-- Connect after a delay -->
65 <div hx-sse:connect="/stream" hx-trigger="load delay:2s">
66
67 <!-- Connect on click -->
68 <button hx-sse:connect="/stream" hx-trigger="click">Start</button>
69
70 <!-- Connect on click, only once -->
71 <button hx-sse:connect="/stream" hx-trigger="click once">Start</button>
72 ```
73
74 ### Using Standard htmx Attributes
75
76 Since the extension intercepts based on Content-Type, any htmx request that returns `text/event-stream` will be streamed automatically:
77
78 ```html
79 <!-- hx-get, hx-post, etc. all work -->
80 <div hx-get="/stream" hx-trigger="load">
81 Waiting...
82 </div>
83
84 <button hx-post="/generate" hx-target="#output">
85 Generate
86 </button>
87 ```
88
89 The difference is that `hx-sse:connect` enables reconnection and `pauseOnBackground` by default, while standard attributes do not.
90
91 ## `hx-sse:close`
92
93 Use `hx-sse:close` to gracefully close an SSE connection when a specific named event is received from the server:
94
95 ```html
96 <div hx-sse:connect="/stream" hx-sse:close="done">
97 Streaming until server sends "done"...
98 </div>
99 ```
100
101 When the server sends `event: done`, the connection is closed and an `htmx:sse:close` event is fired with `detail.reason === "message"`.
102
103 ## Named Events
104
105 SSE messages with an `event:` field are dispatched as DOM events on the source element rather than being swapped:
106
107 ```txt
108 event: notification
109 data: {"title": "New message", "body": "Hello!"}
110 ```
111
112 ```html
113 <div hx-sse:connect="/events"
114 hx-on:notification="alert(event.detail.data)">
115 </div>
116 ```
117
118 Messages without an `event:` field are swapped into the DOM as HTML content.
119
120 SSE messages default to `swapEmpty:false` — if a message contains only `hx-swap-oob` or `<hx-partial>` elements and no
121 main content, the connected element is left untouched. This differs from standard htmx requests where an OOB-only
122 response clears the main target. Override per-element with the [`swapEmpty`](/reference/attributes/hx-swap#swapempty) modifier:
123
124 ```html
125 <!-- Clear the connected element when an empty message arrives -->
126 <div hx-sse:connect="/stream" hx-swap="innerHTML swapEmpty:true">
127 ```
128
129 ## Configuration
130
131 Configure SSE behavior globally via `htmx.config.sse` or per-element via [`hx-config`](/reference/attributes/hx-config) ([HCON](/docs#hx-config) or JSON):
132
133 ```javascript
134 htmx.config.sse = {
135 reconnect: true, // Auto-reconnect on stream end (default: true for hx-sse:connect, false for hx-get)
136 reconnectDelay: 500, // Initial reconnect delay in ms (default: 500)
137 reconnectMaxDelay: 60000, // Maximum reconnect delay in ms (default: 60000)
138 reconnectMaxAttempts: Infinity,// Maximum reconnection attempts (default: Infinity)
139 reconnectJitter: 0.3, // Jitter factor 0-1 for delay randomization (default: 0.3)
140 pauseOnBackground: true // Disconnect when tab is backgrounded (default: true for hx-sse:connect, false for hx-get)
141 };
142 ```
143
144 ```html
145 <!-- Per-element override -->
146 <div hx-sse:connect="/stream" hx-config="sse.reconnectDelay:1s sse.reconnectMaxAttempts:50">
147 ```
148
149 Delay values accept time strings: `"500ms"`, `"1s"`, `"2m"`, or raw milliseconds.
150
151 Defaults for `reconnect` and `pauseOnBackground` depend on how the SSE connection is established:
152
153 | Option | Default (`hx-sse:connect`) | Default (`hx-get`) | Description |
154 |--------|---------------------------|---------------------|-------------|
155 | `reconnect` | `true` | `false` | Auto-reconnect on stream end |
156 | `reconnectDelay` | `500` | `500` | Initial reconnect delay (ms) |
157 | `reconnectMaxDelay` | `60000` | `60000` | Maximum reconnect delay (ms) |
158 | `reconnectMaxAttempts` | `Infinity` | `Infinity` | Maximum reconnection attempts |
159 | `reconnectJitter` | `0.3` | `0.3` | Jitter factor (0-1) for delay randomization |
160 | `pauseOnBackground` | `true` | `false` | Disconnect when tab is backgrounded, reconnect when visible (see [Background Tab Behavior](#background-tab-behavior)) |
161
162 ### Reconnection Strategy
163
164 The extension uses exponential backoff with jitter:
165
166 - **Formula**: `delay = min(reconnectDelay × 2^(attempt-1), reconnectMaxDelay)`
167 - **Jitter**: Adds ±`reconnectJitter` randomization to avoid thundering herd
168 - **Last-Event-ID**: Automatically sent on reconnection if the server provided message IDs (see [Background Tab Behavior](#background-tab-behavior))
169
170 ### Background Tab Behavior
171
172 When `pauseOnBackground` is enabled (the default for `hx-sse:connect`), the extension disconnects the
173 stream when the browser tab is hidden and reconnects when the tab becomes visible again. This exists
174 because some browsers (notably iOS Safari) silently kill SSE connections when the app is backgrounded
175 without firing any error events, leaving the connection in a zombie state.
176
177 **Messages sent by the server while the tab is in the background are not received by the client.** Whether
178 those messages can be recovered depends on your server:
179
180 - If the server includes `id:` fields in its SSE messages, the extension tracks the last received ID and
181 sends it as a `Last-Event-ID` header when reconnecting.
182 - If the server reads the `Last-Event-ID` header and replays missed messages, nothing is lost.
183 - If the server does not send `id:` fields or does not support `Last-Event-ID`, messages sent during the
184 background period are lost.
185
186 #### Example: Resumable Notifications Stream
187
188 **Server** (Python with FastAPI + sse-starlette):
189
190 ```python
191 from fastapi import FastAPI, Request
192 from sse_starlette.sse import EventSourceResponse
193
194 app = FastAPI()
195 notifications = [] # In production, use a database
196
197 @app.get("/notifications")
198 async def sse(request: Request):
199 last_id = request.headers.get("last-event-id")
200
201 async def stream():
202 # Replay any missed messages
203 start = 0
204 if last_id:
205 for i, n in enumerate(notifications):
206 if str(n["id"]) == last_id:
207 start = i + 1
208 break
209 for n in notifications[start:]:
210 yield {"id": str(n["id"]), "data": n["data"]}
211
212 # Stream new messages as they arrive
213 seen = len(notifications)
214 while True:
215 if len(notifications) > seen:
216 for n in notifications[seen:]:
217 yield {"id": str(n["id"]), "data": n["data"]}
218 seen = len(notifications)
219 await asyncio.sleep(0.5)
220
221 return EventSourceResponse(stream())
222 ```
223
224 **Client:**
225
226 ```html
227 <div hx-sse:connect="/notifications" hx-swap="beforeend">
228 <!-- Notifications appear here -->
229 </div>
230 ```
231
232 When the user switches tabs and comes back, the extension reconnects with
233 `Last-Event-ID: <last-received-id>`, and the server replays any notifications
234 that were sent in the meantime.
235
236 ## Events
237
238 ### Connection Lifecycle
239
240 | Event | Cancelable | Detail | Description |
241 |-------|------------|--------|-------------|
242 | `htmx:before:sse:connection` | ✅ | `{connection}` | Before connection attempt (initial or reconnect) |
243 | `htmx:after:sse:connection` | ❌ | `{connection}` | After successful connection |
244 | `htmx:sse:close` | ❌ | `{connection, reason}` | When connection closes (see below) |
245 | `htmx:sse:error` | ❌ | `{error, url, status}` | On stream error |
246
247 The `connection` detail is the actual internal connection object, which includes:
248 - `attempt`: `0` for initial connection, `> 0` for reconnections
249 - `url`: the SSE endpoint URL
250 - `config`: the resolved configuration for this connection
251 - `lastEventId`: the last event ID received
252 - `status`: the HTTP status code (available on `after` events)
253 - `cancelled`: set to `true` in `before` events to cancel the connection
254
255 The `htmx:sse:close` detail includes:
256 - `connection` - the connection object
257 - `reason` - why the connection closed:
258 - `"message"` - closed by `hx-sse:close` matching a named event
259 - `"removed"` - the element was removed from the DOM
260 - `"ended"` - the stream ended naturally or reconnection was exhausted
261 - `"cancelled"` - the initial connection was cancelled via `htmx:before:sse:connection`
262 - `"cleanup"` - closed during element cleanup (e.g., parent swap)
263
264 The `htmx:sse:error` detail includes:
265 - `error`: the error object
266 - `url`: the SSE endpoint URL
267 - `status`: the HTTP status code (only present for non-2xx reconnect responses)
268
269 ### Message Events
270
271 | Event | Cancelable | Detail | Description |
272 |-------|------------|--------|-------------|
273 | `htmx:before:sse:message` | ✅ | `{message: {data, event, id, cancelled}}` | Before processing an SSE message |
274 | `htmx:after:sse:message` | ❌ | `{message: {data, event, id}}` | After processing an SSE message |
275
276 The `message` detail includes:
277 - `data`: the message data (modifiable)
278 - `event`: the event type (modifiable)
279 - `id`: the message ID (if specified)
280 - `cancelled`: set to `true` in the `before` event to skip processing
281
282 ### Event Examples
283
284 **Cancel Connection Based on Condition:**
285 ```javascript
286 document.body.addEventListener('htmx:before:sse:connection', function(evt) {
287 if (evt.detail.connection.attempt > 10) {
288 evt.detail.connection.cancelled = true;
289 }
290 });
291 ```
292
293 **Skip Heartbeat Messages:**
294 ```javascript
295 document.body.addEventListener('htmx:before:sse:message', function(evt) {
296 // Skip heartbeats
297 if (evt.detail.message.event === 'heartbeat') {
298 evt.detail.message.cancelled = true;
299 }
300
301 // Transform data before swap
302 evt.detail.message.data = sanitize(evt.detail.message.data);
303 });
304 ```
305
306 ## Examples
307
308 ### LLM Streaming Response
309
310 A one-off stream using `hx-post` - the server returns `text/event-stream` and the extension handles it automatically:
311
312 ```html
313 <form hx-post="/chat" hx-target="#response" hx-swap="innerHTML">
314 <textarea name="prompt" placeholder="Ask something..."></textarea>
315 <button type="submit">Send</button>
316 </form>
317 <div id="response"></div>
318 ```
319
320 The server streams tokens as SSE messages. Each message replaces the target content, so the user sees the response being "typed" in real-time. `hx-sse:connect` is not needed here. The extension enables streaming via normal `hx-post` (or `hx-get`, `hx-put`, etc.) attributes, based on the response `Content-Type` header.
321
322 ### Live Event Bus
323
324 A persistent connection that pushes targeted updates anywhere on the page using [`<hx-partial>`](/docs#partials-hx-partial):
325
326 ```html
327 <div hx-sse:connect="/events"></div>
328
329 <!-- These can be anywhere on the page -->
330 <div id="feed"></div>
331 <div id="status"></div>
332 ```
333
334 The server uses `<hx-partial>` with `hx-target` to control where each message goes:
335 ```
336 data: <hx-partial hx-target="#feed" hx-swap="beforeend"><div class="event">User joined</div></hx-partial>
337
338 data: <hx-partial hx-target="#feed" hx-swap="beforeend"><div class="event">New comment</div></hx-partial>
339
340 data: <hx-partial hx-target="#status"><span>3 users online</span></hx-partial>
341 ```
342
343 Each `<hx-partial>` targets any element in the DOM via `hx-target` (or `id` as a shorthand). The connection element itself doesn't need `hx-target` or `hx-swap` - the server controls where content goes.
344
345 ### Dashboard with Named Events
346
347 Use named SSE events to route different data types to JavaScript handlers:
348
349 ```html
350 <div hx-sse:connect="/dashboard"
351 hx-on:cpu="htmx.find('#cpu').textContent = event.detail.data"
352 hx-on:memory="htmx.find('#memory').textContent = event.detail.data">
353 <div>CPU: <span id="cpu">--</span></div>
354 <div>Memory: <span id="memory">--</span></div>
355 </div>
356 ```
357
358 Server sends named events:
359 ```
360 event: cpu
361 data: 45%
362
363 event: memory
364 data: 2.3 GB
365 ```
366
367 Named events are dispatched as DOM events (not swapped), so you handle them with `hx-on` or `addEventListener`.
368
369 ## Upgrading from htmx 2.x
370
371 The htmx 2.x SSE extension (`htmx-ext-sse`) has been rewritten for htmx 4.
372
373 ### What Changed
374
375 The 2.x extension was built around `EventSource` and had its own swap mechanism (`sse-swap`) that operated outside of htmx's normal request/response pipeline. The 4.x extension removes all of that. It hooks into htmx's standard request pipeline instead: any htmx request that receives a `Content-Type: text/event-stream` response is automatically streamed as SSE.
376
377 This means:
378 - **Unnamed messages** (no `event:` field) are swapped into the DOM using htmx's normal swap pipeline.
379 - **Named messages** (with an `event:` field) are dispatched as DOM events on the source element. They are not swapped.
380 - `sse-swap` is gone entirely. There is no equivalent, because the extension no longer has its own swap system.
381
382 ### Connecting and Swapping
383
384 **htmx 2.x:**
385 ```html
386 <div sse-connect="/chatroom" sse-swap="message">
387 Contents of this box will be updated in real time
388 with every SSE message received from the chatroom.
389 </div>
390 ```
391
392 **htmx 4.x:**
393 ```html
394 <div hx-sse:connect="/chatroom">
395 Contents of this box will be updated in real time
396 with every SSE message received from the chatroom.
397 </div>
398 ```
399
400 The old `sse-connect` and `sse-close` attributes still work but emit a deprecation warning.
401
402 ### Event Changes
403
404 | htmx 2.x Event | htmx 4.x Event | Notes |
405 |-----------------|-----------------|-------|
406 | `htmx:sseOpen` | `htmx:after:sse:connection` | `detail.connection.attempt === 0` for initial |
407 | `htmx:sseError` | `htmx:sse:error` | `detail.error` contains the error |
408 | `htmx:sseBeforeMessage` | `htmx:before:sse:message` | Set `detail.message.cancelled = true` to skip |
409 | `htmx:sseMessage` | `htmx:after:sse:message` | |
410 | `htmx:sseClose` | `htmx:sse:close` | `detail.reason` indicates why |
411
412 ### Other Changes
413
414 - **No more `EventSource`**: uses `fetch()` + `ReadableStream`, enabling POST requests, custom headers, and cookies.
415 - **Reconnection**: `hx-sse:connect` reconnects automatically with exponential backoff. Configure via `hx-config`.
416 - **Background tab handling**: pauses streams when the tab is backgrounded, reconnects when visible (configurable via `pauseOnBackground`).
417 - **Any HTTP method**: `hx-post`, [`hx-put`](/reference/attributes/hx-put), etc. all work with SSE responses.