Reference

EventSource API

Compressed browser surface. Normative details live in the WHATWG interface section.

Construct

const es = new EventSource("/events");
// CORS cookies:
const es2 = new EventSource("https://api.example.com/events", {
  withCredentials: true,
});

readyState

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

Events

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

What opens vs fails (spec)

Cleanup pattern (SPA)

useEffect(() => {
  const es = new EventSource("/events");
  es.onmessage = (e) => setState(JSON.parse(e.data));
  return () => es.close();
}, []);