# The text/event-stream Format — WebSockets & Server-Sent Events

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

> Read and write the SSE wire format: data, event, id and retry fields, comments and blank-line dispatch.

## Events are just lines of text

An SSE response is an ordinary HTTP response with `Content-Type: text/event-stream` that the server never finishes quickly. Its body is UTF-8 text made of **fields**, one per line, in the form `name: value`. `data:` carries the payload; several `data:` lines in one event are joined with newlines. `event:` gives the event a type name; without it the type is `message`. `id:` sets the event id, which the browser remembers as the *last event id* and sends back when it reconnects. `retry:` tells the browser how many milliseconds to wait before reconnecting. A line starting with `:` is a **comment**; it is ignored, which makes it a handy keep-alive. A **blank line** ends the event and dispatches it. Forgetting that blank line is the most common SSE bug: the browser keeps buffering and nothing ever reaches your handler.

## From server write to browser handler

The server writes text, the stream carries it, the browser's EventSource parses it into events, and your handler runs once per dispatched event.

![Four connected stages in order: server code, text/event-stream response, EventSource parser, event handler.](assets/figures/realtime-web/section-2-map.svg) — Figure 2.1: server -> text/event-stream -> EventSource parser -> handler

## A minimal SSE parser

This Python generator follows the same rules a browser uses (simplified: no `retry`, and only `event` and `id` besides `data`). Running it on a sample stream shows multi-line data and a comment being skipped.

```python
def parse_sse(stream: str):
    event = {"event": "message", "data": [], "id": None}
    for line in stream.splitlines():
        if line == "":                      # blank line = dispatch
            if event["data"]:
                yield event["event"], "\n".join(event["data"]), event["id"]
            event = {"event": "message", "data": [], "id": event["id"]}
            continue
        if line.startswith(":"):            # comment / keep-alive
            continue
        field, _, value = line.partition(":")
        value = value[1:] if value.startswith(" ") else value
        if field == "data":
            event["data"].append(value)
        elif field in ("event", "id"):
            event[field] = value

raw = """: connected

id: 41
data: hello

id: 42
event: price
data: {"symbol": "INFY",
data:  "ltp": 1520.5}

"""
for name, data, last_id in parse_sse(raw):
    print(name, "|", data.replace("\n", "\\n"), "| id =", last_id)
```

Output:

```
message | hello | id = 41
price | {"symbol": "INFY",\n "ltp": 1520.5} | id = 42
```

## Tracing the parser line by line

Follow how each line of the sample stream changes the event being built. Note that nothing is emitted until a blank line arrives.

```python
def parse_sse(stream: str):
    event = {"event": "message", "data": [], "id": None}
    for line in stream.splitlines():
        if line == "":                      # blank line = dispatch
            if event["data"]:
                yield event["event"], "\n".join(event["data"]), event["id"]
            event = {"event": "message", "data": [], "id": event["id"]}
            continue
        if line.startswith(":"):            # comment / keep-alive
            continue
        field, _, value = line.partition(":")
        value = value[1:] if value.startswith(" ") else value
        if field == "data":
            event["data"].append(value)
        elif field in ("event", "id"):
            event[field] = value
```

- Line 9: `: connected` starts with a colon, so it is a comment and is skipped entirely.
- Line 7: The blank line would dispatch, but there is no data yet, so the parser only resets the event.
- Line 16: `id: 41` sets the id; it will stick to later events too unless replaced.
- Line 14: `data: hello`: the single space after the colon is removed, then the value is appended.
- Line 6: Blank line plus collected data: the event is dispatched with the default type `message`.
- Line 16: `id: 42` replaces the remembered id.
- Line 16: `event: price` names this event, so a browser would route it to a `price` listener.
- Line 14: Two `data:` lines are collected separately; they will be joined with a newline.
- Line 6: The final blank line dispatches the `price` event with the joined JSON text.

**Quiz:** A server writes `data: hi\n` and then waits. Why does the browser's handler not run yet?

- [ ] SSE only supports JSON payloads
- [ ] The browser needs an `event:` line first
- [x] The event is not dispatched until a blank line ends it
- [ ] `data:` must be followed by two spaces

*Answer:* The event is not dispatched until a blank line ends it. A blank line terminates and dispatches an event. Until then the browser keeps buffering data lines.
