Core

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.

5 min readUpdated DocumentationEdit this page
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.

TypeScript
TS
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:

  1. Writes status 200 and the SSE headers (see below).
  2. Writes the comment : connected so the client and any proxy see bytes straight away.
  3. Listens for the response's close event, so isOpen turns false when the client disconnects.

Headers

HeaderValue
Content-Typetext/event-stream
Cache-Controlno-cache, no-store, must-revalidate
Connectionkeep-alive
X-Accel-Bufferingno (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

MemberSignatureDescription
send(data: unknown, event?: string, id?: string) => voidWrite one event
comment(text: string) => voidWrite a comment line (: text). Clients ignore it; it keeps the connection active
close() => voidEnd the response. Calling it again does nothing
isOpenreadonly booleanfalse 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 data is sent as is. Anything else is passed through JSON.stringify().
  • Multi-line data is split on \r\n, \r or \n, and each line becomes its own data: line. The browser joins them back with \n.
  • event becomes the event: field. Without it the client receives a default message event.
  • id becomes the id: field. The browser sends the last one back as Last-Event-ID when it reconnects.
  • Line breaks inside id and event are stripped, so a value taken from user input cannot inject extra fields or events.
TypeScript
TS
sse.send({ n: 1 }, 'update', '7')
sse.send('line1\nline2')
sse.comment('ping')
Output
TXT
: 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.

ParameterTypeDefaultDescription
sseSSEConnectionConnection returned by createSSE()
intervalMsnumber30000Milliseconds 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.

TypeScript
TS
const stop = sseHeartbeat(sse, 15_000)   // every 15 s, below a 30 s proxy idle timeout

Resuming 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:

TypeScript
TS
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

JavaScript
JS
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):

TypeScript
TS
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.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY