Real-time

Server-sent event framing

Server-sent events (SSE) carry text events from a server to a client over HTTP. They suit one-way updates such as inventory changes. Browsers expose EventSource, which can reconnect and include the last event ID. A separate HTTP request can send commands in the opposite direction. 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. Source: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events Local examples do not establish third-party integration support.

Formal Syntax & Structure

nodejs syntaxnodejs
Content-Type: text/event-streamid: 2data: {"stock":7}

Working Example

Example Snippetnodejs
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));}
Node.js Reference