• Bytes Route logo

SSE: server sends events to client?!?

Intro

HTTP is unidirectional protocol, this means that only one side can send messages to the counter part. Usually this was done from client to server.

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

This way the responsability is inversed, the client will receive data from the server when new data appears.

How it works

The gist of it is that the client makes a http GET request to the SSE resource and the request is never closed so that the server can continually push 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 client will receive events via '.onmessage' handler.

Example

Here we have a simple example that illustrates the whole operation: SSE Node example.

Additional reading