Server-sent events
Local baseline: Node.js 22.16.0, ECMAScript modules, synthetic data. Run each complete example independently as node main.mjs in a disposable directory. Static ByteMind blocks do not imply live Node execution. SQLite is experimental in this baseline. Third-party integrations below are staged candidates, not installed or validated dependencies.
Serve an SSE event over real loopback HTTP
import http from 'node:http';import {once} from 'node:events';import assert from 'node:assert/strict';const server=http.createServer((req,res)=>{ res.writeHead(200,{'Content-Type':'text/event-stream; charset=utf-8','Cache-Control':'no-cache'}); res.end('id: 2\ndata: '+JSON.stringify({stock:7})+'\n\n');});try { server.listen(0,'127.0.0.1');await once(server,'listening'); const r=await fetch(`http://127.0.0.1:${server.address().port}`,{signal:AbortSignal.timeout(1000)}); assert.equal(r.status,200);assert.match(r.headers.get('content-type'),/^text\/event-stream/); assert.equal(await r.text(),'id: 2\ndata: {"stock":7}\n\n'); console.log('SSE status, type and framing verified');} finally {server.closeAllConnections();await new Promise(r=>server.close(r));}Expected output:
SSE status, type and framing verifiedActual HTTP status, content type and raw framing are asserted. The finite response ends intentionally.
How it works
An event consists of lines such as id, event, data and retry, followed by a blank line. Multiple data lines combine with newline separators. The server sends UTF-8 text with text/event-stream. An event ID is a replay cursor, not a delivery guarantee. Keep a bounded replay log and handle expired cursors with a documented snapshot/resync policy. Authenticate each request, cap connection lifetime, stop timers when clients leave, and account for proxy buffering and idle timeouts. This lab uses fetch to inspect real HTTP bytes, not browser EventSource parsing or automatic reconnection.
Replay events after a known cursor
const log=[{id:2,stock:7},{id:3,stock:6},{id:4,stock:8}];function replay(cursor){ if(cursor<log[0].id-1 || cursor>log.at(-1).id) return 'resync'; return log.filter(e=>e.id>cursor).map(e=>e.id);}console.log(JSON.stringify(replay(2)));console.log(replay(0));console.log(JSON.stringify(replay(4)));Expected output:
[3,4]resync[]Cursor 2 receives later IDs; an expired cursor requires resync; current cursor returns no events.
Common mistakes
Do not insert untrusted strings containing newlines directly into SSE framing. Encode structured data as JSON. Do not assume every proxy flushes writes immediately or every client receives an event just once.
Practice and next steps
Extend the replay fixture with a cursor older than the retained log. Specify a reset response and test that the client requests a snapshot instead of silently missing inventory changes.
Further reading: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events. Related staged reference: node-server-sent-events-lookup (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Server-sent events — knowledge check
Apply the lesson to a fresh scenario and identify the failure boundary.
Which direction does SSE itself carry application events?
How is an event terminated in the wire format?
What if the requested cursor predates all retained events?