SSE: server sends events to client?!?

Cristi Minica

July 21th, 2020

What is SSE?

HTTP is a unidirectional protocol. This means that only one side can send messages to the counterpart. Usually, this action was done from client to server.

This changed when the Server-Sent Events specification described the EventSource API.

This way, the responsibility is inverted. The client will receive data from the server when new data appears.

How it works

The gist of it is that the client makes an HTTP GET request to the SSE resource, and the request is never closed so that the server can continually push the data when needed.

The server has to keep track of connected clients. The messages have to be in a specific format. A block of text terminated by a pair on newlines.

The mime type of the data is 'text/event-stream,' and the connection has to have the 'Connection' header set to 'keep-alive'.

On the client side, an instance of 'EventSource' class should be initialized with the proper endpoint. After that, the client will receive events via '.onmessage' handler.

Hands-on example

In the following, we have a simple example that illustrates the whole operation: SSE Node example.

Additional reading

Don't miss out.

Sign up to our newsletter to stay in the loop.

Share