# Server-Sent Events

> The Server-Sent Events (SSE) is a technology that allows a server to push updates to the client over a single HTTP connection.

## What are Server-Sent Events and when should I use them over WebSockets?

The technology for one-way streaming of text events from the server to the browser over HTTP via the `EventSource` object. Reconnects automatically and is often used for notifications and streaming AI responses.

- Topic: Data Transfer
- Type: technology

## Example

Wrong:

```http
HTTP/1.1 200 OK
Content-Type: application/json

{"msg": "hi"}
```

Right:

```http
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache

id: 1
data: {"msg": "hi"}

```

SSE needs the 'text/event-stream' type and `data:` lines ending with a blank line; `id:` lets the browser resume after reconnecting.

## Common mistakes

- Events arrive all at once because a proxy buffers the response.

## Key points

- The response uses `Content-Type: text/event-stream` and `Cache-Control: no-cache`.
- Each message ends with a blank line, and events have an `id` so reconnects resume with `Last-Event-ID`.
- The `EventSource` is closed with `close()` when the component unmounts.
- Proxy buffering and response compression buffering are turned off for the stream.

## Interview questions

### Can EventSource send an Authorization header?

No, `EventSource` cannot set custom headers. Use cookies, or read the stream with `fetch` and parse events yourself.

### How many SSE connections can a browser keep open?

Over HTTP/1.1 browsers allow about six connections per domain across all tabs. HTTP/2 and later multiplex streams, so the limit rarely matters.

### How does SSE resume after a reconnect?

The browser sends the last received `id` in the `Last-Event-ID` header, so the server can replay missed events.

## Related cards

- [EventSource](https://wonderium.dev/js/event-source.md)
- [WebSocket](https://wonderium.dev/web/websocket.md)
- [Long Polling](https://wonderium.dev/web/long-polling.md)
- [Real-Time Communication](https://wonderium.dev/web/real-time-communication.md)
- [Streaming SSR](https://wonderium.dev/web/streaming-ssr.md)

---

- Level: [Web Platform](https://wonderium.dev/web.md)
- HTML version: https://wonderium.dev/web/server-sent-events
- Last updated: 2026-11-25
