|$ curl https://forge-ai.dev/api/markdown?path=docs/html/sse
$cat docs/server-sent-events-(sse).md
updated Recently·22 min read·published
Server-Sent Events (SSE)
◆HTML◆API◆Advanced
Introduction
Server-Sent Events (SSE) enable servers to push real-time updates to clients over a single HTTP connection using the EventSource API. Unlike WebSockets, SSE is one-directional (server to client) and uses standard HTTP — making it simpler for scenarios like notifications, live feeds, and streaming logs.
Client-Side API
The EventSource interface connects to an SSE endpoint and listens for messages.
sse-client.js
JavaScript
| 1 | const source = new EventSource("/api/events"); |
| 2 | |
| 3 | source.addEventListener("open", () => { |
| 4 | console.log("Connection established"); |
| 5 | }); |
| 6 | |
| 7 | source.addEventListener("message", (event) => { |
| 8 | const data = JSON.parse(event.data); |
| 9 | updateUI(data); |
| 10 | }); |
| 11 | |
| 12 | source.addEventListener("error", (err) => { |
| 13 | console.error("SSE error:", err); |
| 14 | }); |
| 15 | |
| 16 | // Clean up when done |
| 17 | source.close(); |
Server Format
The server sends a text/event-stream response with a specific format. Each message consists of fields separated by newlines, terminated by a double newline.
sse-stream.txt
TEXT
| 1 | data: {"message": "Hello, world!"} |
| 2 | |
| 3 | data: {"progress": 42} |
| 4 | event: progress |
| 5 | id: msg-001 |
| 6 | |
| 7 | : This is a comment (ignored by client) |
| 8 | |
| 9 | retry: 5000 |
Key fields: data (message payload), event (custom event type), id (last event ID for reconnection), retry (reconnection time in ms).
⚠
warning
SSE connections are subject to browser connection limits (typically 6 per domain). The EventSource API does not support custom headers — use a fetch-based polyfill if you need authentication headers.