HTML SSE (Server-Sent Events)

Server-Sent Events (SSE) enable a web page to receive continuous updates from a server via HTTP. Using the EventSource interface, the browser automatically reconnects if the connection drops, making SSE ideal for real-time notifications, live feeds, and status updates.

Key Topics

EventSource API

Example: var source = new EventSource('updates'); connects to a server endpoint that streams events.

Receiving Server Events

Use source.onmessage to handle incoming messages. The server sends events in a text-based format, prefixed by data:.

SSE Example

This example shows a client receiving messages from the server. A full code sample is provided below (server setup required to send events):

<!DOCTYPE html>
<html>
<body>
    <h1>Server Updates</h1>
    <ul id="messages"></ul>

    <script>
    var source = new EventSource('updates');
    source.onmessage = function(e) {
        var li = document.createElement('li');
        li.textContent = e.data;
        document.getElementById('messages').appendChild(li);
    };
    </script>
</body>
</html>

Explanation: As the server sends events (data: lines), the client appends them to a list, showing live updates without manual refreshes.

Key Takeaways

  • SSE provides a simple, persistent connection from server to client.
  • Use EventSource to subscribe to server updates.
  • No complex polling needed; browser reconnects automatically.
  • Ideal for real-time feeds, notifications, and dashboards.
  • Ensure server endpoints send proper SSE-formatted data.