Reference
Compressed browser surface. Normative details live in the WHATWG interface section.
const es = new EventSource("/events");
// CORS cookies:
const es2 = new EventSource("https://api.example.com/events", {
withCredentials: true,
});
Accept: text/event-stream; cache mode is no-store.readyState === EventSource.CONNECTING (0).| Constant | Value | Meaning |
|---|---|---|
CONNECTING |
0 | Not open yet, or reconnecting after a drop |
OPEN |
1 | Stream open; events can dispatch |
CLOSED |
2 | Dead; UA will not reconnect |
es.addEventListener("open", () => { /* readyState → OPEN */ });
// Default event type from the wire (no event: field)
es.onmessage = (e) => {
console.log(e.data); // string
console.log(e.lastEventId);
console.log(e.origin);
};
// Named types require addEventListener("name", …)
es.addEventListener("job-progress", (e) => {
JSON.parse(e.data);
});
es.onerror = () => {
// Fires on reconnect path AND on fatal failure.
// Inspect es.readyState: CONNECTING = retrying, CLOSED = stopped.
};
es.close(); // → CLOSED, stops retries
Content-Type: text/event-stream
close()
CONNECTING, wait retry, fetch again
(may send Last-Event-ID)
useEffect(() => {
const es = new EventSource("/events");
es.onmessage = (e) => setState(JSON.parse(e.data));
return () => es.close();
}, []);