Skip to main content

Server-sent events

A live feed of edits on Wikipedia and other Wikimedia wikis, from the public EventStreams service. The server pushes every change over server-sent events, and the app keeps the newest few on screen.

intermediaterealtimeuseListenerstreaming
import { useListener } from "@hyper-fetch/react";
import { useState } from "react";

import { onRecentChange, type RecentChange, socket } from "./api";

// The stream sends dozens of events per second. Keeping only the newest ones bounds memory and rendering.
const MAX_ITEMS = 15;

export const App = () => {
const [changes, setChanges] = useState<RecentChange[]>([]);
const [received, setReceived] = useState(0);
const [hideBots, setHideBots] = useState(true);

// Subscribes while mounted. `connected` follows the EventSource connection.
const { connected, connecting, onEvent } = useListener(onRecentChange);

onEvent(({ data }) => {
setReceived((count) => count + 1);
if (hideBots && data.bot) return;
setChanges((prev) => [data, ...prev].slice(0, MAX_ITEMS));
});

let status = "Paused";
if (connected) status = "Live";
else if (connecting) status = "Connecting...";

return (
<main className="container">
<hgroup>
<h1>Wikipedia, live</h1>
<p>Every edit on Wikimedia wikis, pushed by the server over server-sent events.</p>
</hgroup>
<article>
<header className="toolbar">
<span aria-busy={connecting && !connected}>
<strong>{status}</strong> <small className="muted">· {received} events received</small>
</span>
<div className="controls">
<label>
<input
type="checkbox"
role="switch"
checked={hideBots}
onChange={(event) => setHideBots(event.target.checked)}
/>
Hide bots
</label>
{/* Disconnecting closes the EventSource, so the server stops sending. Connecting opens a new one. */}
{connected || connecting ? (
<button type="button" className="outline secondary" onClick={socket.disconnect}>
Pause
</button>
) : (
<button type="button" onClick={socket.connect}>
Resume
</button>
)}
</div>
</header>
{changes.length === 0 && <p className="muted">Waiting for the first edit...</p>}
<ul className="feed">
{changes.map((change) => (
<li key={change.meta.id}>
<mark>{change.type}</mark>{" "}
<a href={change.title_url} target="_blank" rel="noreferrer">
{change.title}
</a>
<br />
<small className="muted">
{change.wiki} · {change.user} · {new Date(change.timestamp * 1000).toLocaleTimeString()}
</small>
</li>
))}
</ul>
</article>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/server-sent-events hyper-fetch-react-server-sent-events && cd hyper-fetch-react-server-sent-events && npm install && npm run dev
What it shows
  1. ServerSentEventsAdapter gives a socket client the browser's EventSource as its transport.
  2. decode maps messages from a server that does not send { topic, data } to a listener topic.
  3. useListener receives every event while the component is mounted.
  4. Pause and resume close and reopen the connection with socket.disconnect() and socket.connect().
  5. A capped list keeps memory and rendering flat on a stream with dozens of events per second.

How it works​

  1. api.ts creates the socket with createSocketClient({ url, adapter: ServerSentEventsAdapter() }). It is the same socket API as for WebSockets; only the adapter changes.

  2. Wikimedia sends plain JSON objects. By default the adapter reads topic and data from each message, so the decode adapter option sends every message to one topic:

    adapterOptions: {
    decode: (event) => ({ topic: "recentchange", data: JSON.parse(event.data) }),
    },
  3. onRecentChange is a listener for that topic, typed with the RecentChange fields the UI reads.

  4. App calls useListener(onRecentChange). onEvent counts every event, skips bots when the switch is on and keeps the newest MAX_ITEMS changes.

  5. Pause calls socket.disconnect(), which closes the EventSource, so the server stops sending and connected turns false. Resume calls socket.connect(). If the connection drops on its own, the adapter reconnects.

When to use it
  • Live feeds, notifications and progress updates that only flow from the server to the browser.
  • Servers and proxies where WebSockets are not available but plain HTTP is.
  • Any stream of JSON events, including APIs that use their own message format.

Summary

ServerSentEventsAdapter and a decode function connect a socket client to any SSE endpoint. useListener delivers the events, and disconnect() / connect() pause and resume the stream.