Server-Sent Events explained

Server-Sent Events are a great way to solve one particular shortage of HTTP protocol, which is an asynchronous server to client communication.

HTTP itself is a request-response protocol and this is great – until you need to implement notifications, direct messages, or a similar feature. A backend server cannot send a message if the client didn’t ask for it explicitly.

Of course, there are WebSockets, but are we aware of the alternatives? Server-Sent Events is a technology, which allows us to push messages from a server to a browser in an asynchronous way. This is possible only in that direction, but isn’t it exactly what we miss in HTTP?

HTTP Streaming

Usually, the browser checks the Content-Length response header to check if the response was sent completely or is there any data left to wait for. However, there are situations, where we can process just a part of data without waiting for the whole response. For such a scenario, HTTP/1.1 introduced the chunked transfer encoding. A server can send the response in parts, sending for each of them its length and then its payload.

Why is this important for us? We can use this mechanism to send events! We can send those “chunks” asynchronously as a response to the client each time the event occurs.

Server-Sent Events

Server-Sent Events is a standardized client-side API for processing events sent via HTTP Streaming. Each of those events consists of a name of the event and its payload in the following format:

event: some-event-name
data: some important event data

On the client-side, all we need to do is to create EventSource object and define listeners run when an event with a specified name was received. The API implementation in our browsers takes care of making the request itself, reading the events and passing them to the defined listener methods.

var source = new EventSource("/events");

source.addEventListener("something-happened", function(e) {
    document.body.innerHTML += + "<br>";

On the screenshot below, we see, that the request made by the browser when we created an EventSource object is just an ordinary HTTP request, but with the Accept header set to text/event-stream, which tells the server, that we expect to use Server-Sent Events.

The response has the Transfer-encoding header with value set to chunked and there is no Content-Length header. Each part is preceded with its size in hexadecimal format and each part contain the event’s name after the event: prefix and then below its payload with data: prefix.

comments powered by Disqus