Server-Sent Events (SSE)
Stream real-time updates from Node.js to the browser with createSSE() and sseHeartbeat() from @axiljs/core: event framing, IDs, heartbeats and disconnects.
On this page9
createSSE() turns an AxilJS response into a Server-Sent Events stream: a long-lived HTTP response with Content-Type: text/event-stream that the server writes events to as they happen. Browsers read it with the built-in EventSource API, which reconnects on its own. SSE runs over plain HTTP/1.1, so there is no protocol upgrade and it passes through most proxies.
Use SSE for one-way, server-to-client updates: live dashboards, notifications, job progress and streamed AI responses. For two-way messaging, use WebSockets.
1import { Application, createSSE, sseHeartbeat } from '@axiljs/core'
2
3const app = new Application()
4
5app.get('/events', (_req, res) => {
6 const sse = createSSE(res)
7 const stopHeartbeat = sseHeartbeat(sse)
8
9 sse.send({ message: 'Connected' }, 'connect')
10
11 const timer = setInterval(() => {
12 sse.send({ time: Date.now() }, 'update')
13 }, 1000)
14
15 // Client went away: stop producing events
16 res.raw.on('close', () => {
17 clearInterval(timer)
18 stopHeartbeat()
19 })
20})createSSE(res)
Starts the stream and returns an SSEConnection. It does three things immediately:
- Writes status
200and the SSE headers (see below). - Writes the comment
: connectedso the client and any proxy see bytes straight away. - Listens for the response's
closeevent, soisOpenturnsfalsewhen the client disconnects.
Headers
| Header | Value |
|---|---|
Content-Type | text/event-stream |
Cache-Control | no-cache, no-store, must-revalidate |
Connection | keep-alive |
X-Accel-Buffering | no (stops nginx from buffering the stream) |
Access-Control-Allow-Origin | *, only when no earlier middleware or handler set it |
If you register cors() or set Access-Control-Allow-Origin yourself before calling createSSE(), that value is kept.
Note
createSSE() sends the headers at once. After that, an error passed to next() can no longer produce a JSON error body; the framework just ends the response. Validate input and check auth before you open the stream.
SSEConnection
| Member | Signature | Description |
|---|---|---|
send | (data: unknown, event?: string, id?: string) => void | Write one event |
comment | (text: string) => void | Write a comment line (: text). Clients ignore it; it keeps the connection active |
close | () => void | End the response. Calling it again does nothing |
isOpen | readonly boolean | false after close() or once the client disconnects |
send() and comment() do nothing once the connection is closed, so a late timer callback cannot write to a finished response.
How send() frames an event
- A string
datais sent as is. Anything else is passed throughJSON.stringify(). - Multi-line data is split on
\r\n,\ror\n, and each line becomes its owndata:line. The browser joins them back with\n. eventbecomes theevent:field. Without it the client receives a defaultmessageevent.idbecomes theid:field. The browser sends the last one back asLast-Event-IDwhen it reconnects.- Line breaks inside
idandeventare stripped, so a value taken from user input cannot inject extra fields or events.
sse.send({ n: 1 }, 'update', '7')
sse.send('line1\nline2')
sse.comment('ping'): connected
id: 7
event: update
data: {"n":1}
data: line1
data: line2
: ping
send() has no parameter for the SSE retry: field. The exported SSEEvent type lists data, event, id and retry for your own typings, but createSSE() never writes retry:.
sseHeartbeat(sse, intervalMs?)
Proxies and load balancers often close connections that stay silent for 30 to 60 seconds. sseHeartbeat() sends a : heartbeat comment on a timer to prevent that.
| Parameter | Type | Default | Description |
|---|---|---|---|
sse | SSEConnection | Connection returned by createSSE() | |
intervalMs | number | 30000 | Milliseconds between heartbeat comments |
It returns a function that stops the timer. The timer also clears itself on the first tick after the connection closes, but calling the stop function on disconnect releases it straight away.
const stop = sseHeartbeat(sse, 15_000) // every 15 s, below a 30 s proxy idle timeoutResuming with Last-Event-ID
When the browser reconnects, it sends the last id it received. Read it from the request headers and replay what the client missed:
1app.get('/orders/stream', async (req, res) => {
2 const lastId = req.headers['last-event-id'] as string | undefined
3 const sse = createSSE(res)
4
5 for (const order of await orders.since(lastId)) {
6 sse.send(order, 'order', String(order.seq))
7 }
8})Browser client
1const source = new EventSource('/events')
2
3source.addEventListener('connect', (e) => console.log(JSON.parse(e.data)))
4source.addEventListener('update', (e) => console.log(JSON.parse(e.data)))
5source.onmessage = (e) => console.log('unnamed event', e.data) // events sent without a type
6source.onerror = () => console.log('disconnected, the browser will retry')Call source.close() to stop the browser reconnecting.
Streaming AI responses
The AI middleware in @axiljs/ai uses createSSE() to stream chat output, sending each chunk as a delta event. The same pattern works for any async iterator (generateTokens stands for your own token source):
1app.post('/chat', async (req, res) => {
2 const sse = createSSE(res)
3 for await (const chunk of generateTokens(req.body.prompt)) {
4 if (!sse.isOpen) break // stop generating when the client leaves
5 sse.send({ delta: chunk }, 'delta')
6 }
7 sse.close()
8})Tip
Each SSE client holds one open connection. When you run several workers or instances, an event produced on one process only reaches clients connected to that process. Fan out through a shared broker; see Scaling.
Related
Was this page helpful?