|$ 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)

HTMLAPIAdvanced
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
1const source = new EventSource("/api/events");
2
3source.addEventListener("open", () => {
4 console.log("Connection established");
5});
6
7source.addEventListener("message", (event) => {
8 const data = JSON.parse(event.data);
9 updateUI(data);
10});
11
12source.addEventListener("error", (err) => {
13 console.error("SSE error:", err);
14});
15
16// Clean up when done
17source.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
1data: {"message": "Hello, world!"}
2
3data: {"progress": 42}
4event: progress
5id: msg-001
6
7: This is a comment (ignored by client)
8
9retry: 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.