tRPC subscriptions
A chat with two rooms. Messages are posted with a tRPC mutation and arrive through a tRPC subscription, streamed over
Server-Sent Events into useListener. A bot answers every message a second later, so you see events that the client did
not ask for. Open the app in a second tab to chat between them.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useListener, useSubmit } from "@hyper-fetch/react";
import { type FormEvent, useState } from "react";
import type { Message } from "../server/router";
import { realtime, sdk } from "./api";
const rooms = ["general", "random"] as const;
const author = `guest-${Math.floor(Math.random() * 1000)}`;
const Room = ({ room }: { room: (typeof rooms)[number] }) => {
const [messages, setMessages] = useState<Message[]>([]);
const [text, setText] = useState("");
// The payload is the procedure input. Another room is another subscription.
const { status, connected, extra, error, onEvent } = useListener(
realtime.chat.onMessage.$listener.setPayload({ room }),
);
const { submit, submitting } = useSubmit(sdk.chat.post.$mutation);
// `data` is the event without the `tracked()` wrapper, the id is in `extra.eventId`.
onEvent(({ data }) => {
setMessages((current) => (current.some((message) => message.id === data.id) ? current : [...current, data]));
});
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const response = await submit({ payload: { room, author, text } });
if (response.success) setText("");
};
return (
<article>
<header className="toolbar">
<strong>#{room}</strong>
<small className="muted" aria-busy={status === "starting"}>
{connected ? "connected" : "offline"} / {status} / last event {extra?.eventId ?? "-"}
</small>
</header>
{status === "failed" && <p className="error">Subscription failed: {error?.message}</p>}
<ul className="list messages">
{messages.map((message) => (
<li key={message.id}>
<span>
<strong>{message.author === author ? "you" : message.author}</strong> {message.text}
</span>
<small className="muted">#{message.id}</small>
</li>
))}
{messages.length === 0 && <li className="muted">No messages yet. Say hi.</li>}
</ul>
<form onSubmit={handleSubmit}>
<fieldset role="group">
<input value={text} onChange={(event) => setText(event.target.value)} placeholder={`Message #${room}`} />
<button type="submit" aria-busy={submitting} disabled={submitting || !text.trim()}>
Send
</button>
</fieldset>
</form>
</article>
);
};
export const App = () => {
const [room, setRoom] = useState<(typeof rooms)[number]>("general");
return (
<main className="container">
<hgroup>
<h1>tRPC subscriptions</h1>
<p>
Messages stream from a tRPC subscription over Server-Sent Events. Open a second tab to chat with yourself.
</p>
</hgroup>
<div role="group">
{rooms.map((name) => (
<button
key={name}
type="button"
className={name === room ? undefined : "outline"}
onClick={() => setRoom(name)}
>
#{name}
</button>
))}
</div>
{/* `key` gives every room a fresh message list. */}
<Room key={room} room={room} />
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/trpc/subscriptions hyper-fetch-trpc-subscriptions && cd hyper-fetch-trpc-subscriptions && npm install && npm run devTrpcSseAdapterconnects a HyperFetchSocketto tRPC subscriptions over Server-Sent Events.TrpcSocketSchema<AppRouter>turns every subscription into a typed$listener, with the input as its payload.useListenersubscribes on mount, restarts when the payload changes and shows thestatusthe server reports.- Tracked events:
tracked(id, message)reaches the client asdata, with the id inextra.eventId. - One handler, two adapters: the same
/api/trpcendpoint serves the mutation (TrpcAdapter) and the stream.
How it works
-
server/router.tshas achat.postmutation and achat.onMessagesubscription. The subscription is an async generator: it yields the last messages of the room, then every new one, each wrapped intracked(message.id, ...). When the client leaves, tRPC abortssignaland the generator stops. -
server/app.tsmounts the router withfetchRequestHandlerinside Hono, and Vite runs it for/apirequests. The fetch adapter answers subscriptions with an SSE stream, so no WebSocket server or second process is needed. -
src/api.tscreates two things that point at the same URL: a client withTrpcAdapter()for the mutation, and a socket withTrpcSseAdapter()for the subscription.export const socket = new Socket({ url, adapter: TrpcSseAdapter() });export const realtime = createSocketSdk<typeof socket, TrpcSocketSchema<AppRouter>>(socket, {camelCaseToKebabCase: false,}); -
RoomcallsuseListener(realtime.chat.onMessage.$listener.setPayload({ room })). The adapter opensGET /api/trpc/chat.onMessage?input={"room":"general"}as anEventSource. Other components listening to the same room share that stream. Switching rooms changes the payload, so the hook stops the old subscription and starts a new one. -
onEventappends each message to the list. The header showsconnected, the hookstatus(startinguntil the server confirms the subscription, thenlistening) andextra.eventIdof the last event. -
If the connection drops, the adapter restarts the subscription with the last event id as
input.lastEventId. The procedure reads it and sends only the messages the client missed.
- Live feeds, chats, notifications or progress updates on top of an existing tRPC backend.
- Server-Sent Events fit when you already serve tRPC over HTTP, including serverless hosts. For many subscriptions per
client, switch the socket to
TrpcWebsocketAdapterandapplyWSSHandler; the listeners stay the same.
Related
TrpcSseAdapter and TrpcSocketSchema turn tRPC subscriptions into typed listeners. useListener handles subscribing,
switching inputs and cleanup, and tracked event ids let a reconnect pick up where the stream stopped.
