You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: www/features/eventsource.md
+75Lines changed: 75 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -203,13 +203,88 @@ When a connection drops, hyperscript automatically reconnects with exponential b
203
203
204
204
Calling `close()` stops reconnection. Calling `open()` again resumes it.
205
205
206
+
### `fetch` as Stream
207
+
208
+
The SSE extension also adds a `Stream` conversion to the [`fetch`](/commands/fetch) command.
209
+
210
+
This is useful for one-shot SSE streams (AI chat responses, progress updates, file processing) where you don't need the long-lived connection management of `eventsource`.
211
+
212
+
~~~hyperscript
213
+
fetch /api/generate as Stream
214
+
~~~
215
+
216
+
The result is a stream object. Named events from the server are dispatched on the current element, and unnamed messages can be iterated with a `for` loop:
217
+
218
+
#### Named events
219
+
220
+
If the server sends named SSE events (with an `event:` field), they are dispatched
221
+
as DOM events on the element that initiated the fetch. Handle them with `on`:
222
+
223
+
~~~hyperscript
224
+
on click
225
+
fetch /api/process as Stream
226
+
end
227
+
on status -- from SSE stream
228
+
put event.detail.data into #progress
229
+
end
230
+
~~~
231
+
232
+
#### Iterating messages
233
+
234
+
Unnamed messages (plain `data:` lines with no `event:` field) are available as
235
+
an async iterable. Use `for ... in the result` to process each message as it
236
+
arrives:
237
+
238
+
~~~hyperscript
239
+
on click
240
+
fetch /api/chat as Stream
241
+
for message in the result
242
+
put message at end of #output
243
+
end
244
+
end
245
+
~~~
246
+
247
+
The loop body runs once per message, blocking until the next one arrives. When the stream closes, the loop exits normally.
248
+
249
+
#### Waiting for the stream to end
250
+
251
+
The stream fires a `streamEnd` event on the element when the server closes the
252
+
connection:
253
+
254
+
~~~hyperscript
255
+
on click
256
+
fetch /api/export as Stream
257
+
wait for streamEnd
258
+
put "Done!" into me
259
+
end
260
+
~~~
261
+
262
+
#### Error handling
263
+
264
+
If the stream encounters an error, a `streamError` event is dispatched on the element with an `error` property in the detail:
265
+
266
+
~~~hyperscript
267
+
on click
268
+
fetch /api/generate as Stream
269
+
on streamError from me
270
+
put "Connection lost" into #status
271
+
end
272
+
end
273
+
~~~
274
+
275
+
{% note %}
276
+
Without the SSE extension loaded, `fetch ... as Stream` throws an error telling you to include the extension.
0 commit comments