iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

HTML SSE

Server-Sent Events (SSE) is a simple one-way streaming protocol: the server pushes text events to the browser over a single long-lived HTTP connection.

How it works

  1. The browser opens an EventSource to a URL.
  2. The server keeps the response open and writes events in a tiny line-based format.
  3. Each event triggers a message event on the client.
  4. If the connection drops, the browser reconnects automatically.

Client side

const stream = new EventSource('/updates');

stream.onmessage = function (e) {
    console.log('Update:', e.data);
};

stream.addEventListener('price', e => {
    console.log('Named price event:', e.data);
});

stream.onerror = () => console.warn('Connection lost — will reconnect.');

SSE vs WebSocket

SSEWebSocket
DirectionServer → client only.Both ways.
ProtocolHTTP.Custom ws://.
Auto-reconnectBuilt in.You write it.
Best forLive feeds, progress, notifications.Chat, games, collaborative editing.
Tip: SSE is enough for most "push" use cases. Only reach for WebSocket when the client also needs to send messages frequently.

Example

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML SSE</title>
</head>
<body>

<h1>HTML SSE</h1>
<p>This is a demo page for the "HTML SSE" lesson.</p>

</body>
</html>
Try it Yourself »

Exercise

Open a server-sent events stream.

const es = new ('/stream');

Test yourself

Q1. Server-Sent Events deliver…
Q2. In JS, consume SSE via…
Q3. SSE auto-reconnects on…

Discussion

Loading…