HomeAbout

Server-Sent Events

What is server-sent events

Traditionally, client sends request to server to receive new data.

With server-sent events, server can send new data to client at any time.

This is a one-way communication from server to client.

  • can't send events from client to server.
const evtSource = new EventSource("sse.php"); const eventList = document.querySelector("ul"); evtSource.onmessage = (e) => { const newElement = document.createElement("li"); newElement.textContent = `message: ${e.data}`; eventList.appendChild(newElement); };

Setting multiple events:

const sse = new EventSource("/api/v1/sse"); /* * This will listen only for events * similar to the following: * * event: notice * data: useful data * id: some-id */ sse.addEventListener("notice", (e) => { console.log(e.data); }); /* * Similarly, this will listen for events * with the field `event: update` */ sse.addEventListener("update", (e) => { console.log(e.data); }); /* * The event "message" is a special case, as it will capture events without an event field as well as events that have the specific type `event: message`. It will not trigger on any other event type. */ sse.addEventListener("message", (e) => { console.log(e.data); });

vs Websocket

Unlike WebSocket, server-sent events keep the connection alive and automatically reconnect if the connection is lost.

With WebSocket, you need to handle the connection and reconnection logic manually. Using onclose or onerror events.

AboutContact