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.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
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>
);
};
npx 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 devServerSentEventsAdaptergives a socket client the browser'sEventSourceas its transport.decodemaps messages from a server that does not send{ topic, data }to a listener topic.useListenerreceives every event while the component is mounted.- Pause and resume close and reopen the connection with
socket.disconnect()andsocket.connect(). - A capped list keeps memory and rendering flat on a stream with dozens of events per second.
How it works
-
api.tscreates the socket withcreateSocketClient({ url, adapter: ServerSentEventsAdapter() }). It is the same socket API as for WebSockets; only the adapter changes. -
Wikimedia sends plain JSON objects. By default the adapter reads
topicanddatafrom each message, so thedecodeadapter option sends every message to one topic:adapterOptions: {decode: (event) => ({ topic: "recentchange", data: JSON.parse(event.data) }),}, -
onRecentChangeis a listener for that topic, typed with theRecentChangefields the UI reads. -
AppcallsuseListener(onRecentChange).onEventcounts every event, skips bots when the switch is on and keeps the newestMAX_ITEMSchanges. -
Pause calls
socket.disconnect(), which closes theEventSource, so the server stops sending andconnectedturnsfalse. Resume callssocket.connect(). If the connection drops on its own, the adapter reconnects.
- 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.
Related
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.
