# EventSource

> The `EventSource` JS object receives a stream of events sent by a server over HTTP.

## How do I receive server-sent events in JavaScript?

The object that opens a one-way stream of server-sent events over a regular HTTP connection and reconnects automatically. Simpler than `WebSocket` when only the server needs to push data, such as notifications or streamed AI responses.

- Topic: Fetching Data
- Type: object
- Browser support: Chrome 6+, Chrome Android 18+, Edge 79+, Firefox 6+, Firefox Android 45+, Safari 5+, Safari iOS 5+

## Example

Wrong:

```js
const source = new EventSource('/events', {
  headers: { Authorization: `Bearer ${token}` },
});
```

Right:

```js
const source = new EventSource('/events', { withCredentials: true });
source.addEventListener('message', (e) => render(JSON.parse(e.data)));
window.addEventListener('pagehide', () => source.close());
```

`EventSource` ignores custom headers, so auth goes through cookies, and the stream is closed when the page goes away.

## Common mistakes

- Using `EventSource` for requests that need custom headers or a request body, which it does not support.

## Key points

- The stream is closed with `close()` when the component or page no longer needs it.
- The server responds with the 'text/event-stream' content type.

## Interview questions

### Does EventSource reconnect automatically?

Yes. If the connection drops, it reconnects after a delay and sends the 'Last-Event-ID' header so the server can resume.

### Can EventSource send POST requests?

No. It only makes GET requests. For a POST stream, read the `fetch()` response body with a stream reader.

### How do I listen for custom event types?

Use `addEventListener('name', ...)` for events the server sends with an 'event: name' line; `onmessage` gets only unnamed events.

## Related cards

- [Server-Sent Events](https://wonderium.dev/web/server-sent-events.md)
- [WebSocket](https://wonderium.dev/js/web-socket.md)
- [Streaming](https://wonderium.dev/ai/streaming.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/event-source
- Last updated: 2026-11-25
