Chapter 16
Server Sent Events (SSE)
Server-Sent Events (SSE) is a technology that enables a server to send continuous updates or event streams to clients over HTTP. It is a unidirectional communication method where the server pushes data to the client, allowing real-time updates without the need for the client to repeatedly request information. To meet this goal, SSE introduced two components: a new EventSource interface in the browser, which allows the client to receive push notifications from the server as DOM events, and the “event stream” data format, which is used to deliver the individual updates.
Here’s how Server-Sent Events work:
- Establishing a Connection: The client initiates a regular HTTP connection with the server by sending a GET request to a specific URL that handles SSE.
- Server Response: Upon receiving the GET request, the server responds with an HTTP header containing the “Content-Type” field set to “text/event-stream”. This indicates that the server will be sending events rather than a traditional HTTP response.
- Event Stream Format: The server sends events in a specific format. Each event is represented as a separate message and consists of one or more lines. Each line can either be an event field or data field. An event field starts with “event:” followed by the event name, while a data field starts with “data:” followed by the event data.
- Connection Persistence: Unlike traditional HTTP requests, SSE connections persist and remain open until either the server or the client explicitly closes them. This enables the server to send events to the client whenever updates occur.
- Event Lifecycle: The server can send events at any time, and the client receives them immediately. The client-side JavaScript code can listen for these events and perform actions or update the user interface based on the received data.
- Error Handling: SSE connections can handle errors gracefully. If the connection is lost, the client automatically attempts to reconnect, allowing a reliable and uninterrupted stream of events.
- Closing the Connection: The client or server can close the connection at any time. If the client wants to terminate the SSE connection, it can simply close the connection from its end, and the server will recognize that the client is no longer available.
Server-Sent Events are often used for real-time notifications, live feeds, chat applications, or any scenario where continuous updates from the server to clients are required. It provides a lightweight and easy-to-use alternative to WebSockets when bidirectional communication is not necessary.
Event Stream Protocol
An SSE event stream is delivered as a streaming HTTP response:
- The client send a regular HTTP GET request
- The server responds with a custom “text/event-stream” content-type header, and then stream the UTF-8 encoded data.