|
| 1 | +--- |
| 2 | +outline: deep |
| 3 | +--- |
| 4 | + |
| 5 | +# Server-Sent Events |
| 6 | + |
| 7 | +Void provides `void/sse` for producing and consuming Server-Sent Events from ordinary route handlers. It handles event formatting, response headers, keepalives, stream closure, request aborts, and browser `EventSource` parsing. |
| 8 | + |
| 9 | +Use SSE when one HTTP request owns the producer: AI token streaming, progress updates, command output, deployment logs, or incremental status messages. Use `void/live` or an application-level Durable Object when multiple requests need shared fanout, replay, or subscription state. |
| 10 | + |
| 11 | +## Server streams |
| 12 | + |
| 13 | +Return `eventStream()` from a route handler: |
| 14 | + |
| 15 | +```ts |
| 16 | +// routes/api/events.ts |
| 17 | +import { defineHandler } from 'void'; |
| 18 | +import { eventStream } from 'void/sse'; |
| 19 | + |
| 20 | +export const GET = defineHandler((c) => { |
| 21 | + return eventStream( |
| 22 | + async (stream) => { |
| 23 | + await stream.comment('connected'); |
| 24 | + await stream.send({ |
| 25 | + event: 'ready', |
| 26 | + data: { now: Date.now() }, |
| 27 | + }); |
| 28 | + |
| 29 | + const timer = setInterval(() => { |
| 30 | + void stream.send({ event: 'tick', data: { now: Date.now() } }).catch(() => stream.close()); |
| 31 | + }, 1000); |
| 32 | + |
| 33 | + await stream.closed; |
| 34 | + clearInterval(timer); |
| 35 | + }, |
| 36 | + { |
| 37 | + signal: c.req.raw.signal, |
| 38 | + }, |
| 39 | + ); |
| 40 | +}); |
| 41 | +``` |
| 42 | + |
| 43 | +`eventStream()` returns a `Response` immediately with these default headers: |
| 44 | + |
| 45 | +```http |
| 46 | +Content-Type: text/event-stream; charset=utf-8 |
| 47 | +Cache-Control: no-cache, no-transform |
| 48 | +X-Accel-Buffering: no |
| 49 | +``` |
| 50 | + |
| 51 | +When the `start` callback returns, the stream closes. Long-lived streams should wait on `stream.closed`, a producer promise, or an application cancellation signal before returning. |
| 52 | + |
| 53 | +## Sending events |
| 54 | + |
| 55 | +Use `send()` for SSE messages and `comment()` for comments: |
| 56 | + |
| 57 | +```ts |
| 58 | +await stream.send({ |
| 59 | + id: 'evt_1', |
| 60 | + event: 'post.update', |
| 61 | + retry: 1000, |
| 62 | + data: { id: 'post_123', likes: 10 }, |
| 63 | +}); |
| 64 | + |
| 65 | +await stream.comment('still connected'); |
| 66 | +``` |
| 67 | + |
| 68 | +`data` may be a string or JSON-serializable value. Strings are sent as-is; other values are serialized with `JSON.stringify()`. Multi-line strings are split into multiple `data:` lines. Binary data is rejected because SSE is text-only. |
| 69 | + |
| 70 | +`event`, `id`, and `retry` are validated before writing so accidental frame injection is rejected. Writes after close reject with `SseStreamClosedError`. |
| 71 | + |
| 72 | +If you already serialized the payload, use `formatSseText()` for lower-level formatting while keeping the same `id`, `event`, and `retry` validation: |
| 73 | + |
| 74 | +```ts |
| 75 | +import { formatSseText } from 'void/sse'; |
| 76 | + |
| 77 | +const frame = formatSseText({ |
| 78 | + event: 'post.update', |
| 79 | + data: JSON.stringify({ id: 'post_123', likes: 10 }), |
| 80 | +}); |
| 81 | +``` |
| 82 | + |
| 83 | +## Keepalives |
| 84 | + |
| 85 | +Keepalives are enabled by default every 15 seconds: |
| 86 | + |
| 87 | +```ts |
| 88 | +return eventStream(start); |
| 89 | +``` |
| 90 | + |
| 91 | +Disable them or customize the interval and comment text: |
| 92 | + |
| 93 | +```ts |
| 94 | +return eventStream(start, { keepAlive: false }); |
| 95 | + |
| 96 | +return eventStream(start, { |
| 97 | + keepAlive: { intervalMs: 5000, comment: 'ping' }, |
| 98 | +}); |
| 99 | +``` |
| 100 | + |
| 101 | +The interval must be a positive finite number. |
| 102 | + |
| 103 | +## Last Event ID |
| 104 | + |
| 105 | +Browsers send `Last-Event-ID` when reconnecting after an event with an `id` field. Use `getLastEventId()` to resume from your own storage: |
| 106 | + |
| 107 | +```ts |
| 108 | +import { getLastEventId } from 'void/sse'; |
| 109 | + |
| 110 | +export const GET = defineHandler((c) => { |
| 111 | + const lastId = getLastEventId(c.req.raw); |
| 112 | + return eventStream(async (stream) => { |
| 113 | + await stream.send({ id: nextId(lastId), data: await loadNextItem(lastId) }); |
| 114 | + }); |
| 115 | +}); |
| 116 | +``` |
| 117 | + |
| 118 | +`void/sse` does not store or replay events. Persist event offsets in your own database, queue, or Durable Object when replay matters. |
| 119 | + |
| 120 | +## Client |
| 121 | + |
| 122 | +Use `connectEventStream()` from the browser-only `void/sse/client` subpath: |
| 123 | + |
| 124 | +```ts |
| 125 | +import { connectEventStream } from 'void/sse/client'; |
| 126 | + |
| 127 | +const stream = connectEventStream<{ |
| 128 | + ready: { now: number }; |
| 129 | + tick: { now: number }; |
| 130 | +}>('/api/events', { |
| 131 | + withCredentials: true, |
| 132 | +}); |
| 133 | + |
| 134 | +const offReady = stream.on('ready', (event) => { |
| 135 | + console.log(event.data.now); |
| 136 | +}); |
| 137 | + |
| 138 | +stream.on('tick', (event) => { |
| 139 | + console.log(event.data.now); |
| 140 | +}); |
| 141 | + |
| 142 | +offReady(); |
| 143 | +stream.close(); |
| 144 | +``` |
| 145 | + |
| 146 | +The client wraps native `EventSource`. It supports cookie credentials and typed event handlers, but it does not support request bodies or arbitrary headers. Use cookie auth, signed URLs, or a fetch-based streaming route when you need custom headers. |
| 147 | + |
| 148 | +JSON parsing is the default. Set `parse: 'text'` or pass a custom parser for non-JSON payloads: |
| 149 | + |
| 150 | +```ts |
| 151 | +const logs = connectEventStream('/api/logs', { parse: 'text' }); |
| 152 | + |
| 153 | +logs.on('line', (event) => { |
| 154 | + console.log(event.data); |
| 155 | +}); |
| 156 | +``` |
| 157 | + |
| 158 | +## Auth |
| 159 | + |
| 160 | +SSE routes are ordinary route handlers, so use the same auth checks you use for JSON routes: |
| 161 | + |
| 162 | +```ts |
| 163 | +import { requireAuth } from 'void/auth'; |
| 164 | + |
| 165 | +export const GET = defineHandler(async (c) => { |
| 166 | + const user = await requireAuth(c); |
| 167 | + |
| 168 | + return eventStream(async (stream) => { |
| 169 | + await stream.send({ event: 'ready', data: { userId: user.id } }); |
| 170 | + await stream.closed; |
| 171 | + }); |
| 172 | +}); |
| 173 | +``` |
| 174 | + |
| 175 | +Native `EventSource` can send cookies with `withCredentials: true`. For non-cookie auth, generate a short-lived signed URL and validate it in the route handler. |
| 176 | + |
| 177 | +## When to use SSE |
| 178 | + |
| 179 | +Plain SSE is enough when the producer belongs to the same request that opened the stream: |
| 180 | + |
| 181 | +- AI token streaming |
| 182 | +- One-off progress updates |
| 183 | +- Command output |
| 184 | +- Per-request deployment or build logs |
| 185 | +- Incremental status for a long-running action |
| 186 | + |
| 187 | +Use a higher-level realtime primitive when you need cross-request fanout, rooms, replay buffers, subscriptions, database change streams, or multi-region coordination. |
0 commit comments