# The EventSource API in the Browser — WebSockets & Server-Sent Events

Source: https://www.skillbyai.com/en/realtime-web/rt-eventsource

> Open an SSE stream with EventSource, handle named events, errors and readyState, and close it cleanly.

## What EventSource does for you

`new EventSource(url)` sends a GET request with `Accept: text/event-stream`, parses the stream and fires DOM events. Unnamed events arrive at `onmessage`; named events (`event: status`) only reach `addEventListener('status', ...)`, a frequent source of "my handler never fires". Each `MessageEvent` has `data` (always a string, so you call `JSON.parse` yourself) and `lastEventId`. `readyState` is `0` (CONNECTING), `1` (OPEN) or `2` (CLOSED). If the connection drops, the browser **reconnects automatically**, sending the `Last-Event-ID` header, and fires `error` while it retries. It gives up and moves to CLOSED if the server answers with a non-200 status or a wrong content type, or if you call `close()`. The constructor accepts `{ withCredentials: true }` for cross-origin cookies. What it cannot do: send POST bodies, set custom headers such as `Authorization`, or read binary data.

## Listening to an order-status stream

Named and unnamed events use different subscription styles. The `error` handler checks `readyState` to tell "retrying" from "gave up".

```js
const source = new EventSource('/api/orders/stream', { withCredentials: true });

source.addEventListener('open', () => console.log('stream open'));

// Unnamed events (no "event:" line) arrive as "message".
source.onmessage = (e) => console.log('message', e.data);

// Named events need addEventListener with the same name.
source.addEventListener('status', (e) => {
  const { orderId, status } = JSON.parse(e.data);
  console.log(orderId, status, 'lastEventId =', e.lastEventId);
});

source.onerror = () => {
  // readyState 0 = CONNECTING (browser is retrying), 2 = CLOSED (gave up)
  console.log('error, readyState =', source.readyState);
};

// When the page no longer needs updates:
// source.close();
```

## Close streams you no longer need

Single-page apps often open an EventSource in a component and forget to `close()` it on navigation. Each forgotten stream keeps a connection and a server-side handler alive. Close it in your cleanup hook, for example `ngOnDestroy` or a React effect's cleanup function.

## A radio that retunes itself

EventSource is like a car radio with auto-retune. If you drive under a flyover and lose the station, it keeps searching and picks the same station back up, and the station can even replay what you missed if it knows where you dropped off.

**Quiz:** The server sends `event: status` events, but `source.onmessage` never fires. What is the fix?

- [x] Add `source.addEventListener('status', handler)`
- [ ] Send the events as binary
- [ ] Set `readyState` to 1 manually
- [ ] Use `withCredentials: false`

*Answer:* Add `source.addEventListener('status', handler)`. `onmessage` only receives events with no `event:` field (type `message`). Named events need a listener registered under that name.
