Skip to main content

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.

advancedtrpcrealtimeuseListeneruseSubmit
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>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/trpc/subscriptions hyper-fetch-trpc-subscriptions && cd hyper-fetch-trpc-subscriptions && npm install && npm run dev
What it shows
  1. TrpcSseAdapter connects a HyperFetch Socket to tRPC subscriptions over Server-Sent Events.
  2. TrpcSocketSchema<AppRouter> turns every subscription into a typed $listener, with the input as its payload.
  3. useListener subscribes on mount, restarts when the payload changes and shows the status the server reports.
  4. Tracked events: tracked(id, message) reaches the client as data, with the id in extra.eventId.
  5. One handler, two adapters: the same /api/trpc endpoint serves the mutation (TrpcAdapter) and the stream.

How it works​

  1. server/router.ts has a chat.post mutation and a chat.onMessage subscription. The subscription is an async generator: it yields the last messages of the room, then every new one, each wrapped in tracked(message.id, ...). When the client leaves, tRPC aborts signal and the generator stops.

  2. server/app.ts mounts the router with fetchRequestHandler inside Hono, and Vite runs it for /api requests. The fetch adapter answers subscriptions with an SSE stream, so no WebSocket server or second process is needed.

  3. src/api.ts creates two things that point at the same URL: a client with TrpcAdapter() for the mutation, and a socket with TrpcSseAdapter() for the subscription.

    export const socket = new Socket({ url, adapter: TrpcSseAdapter() });
    export const realtime = createSocketSdk<typeof socket, TrpcSocketSchema<AppRouter>>(socket, {
    camelCaseToKebabCase: false,
    });
  4. Room calls useListener(realtime.chat.onMessage.$listener.setPayload({ room })). The adapter opens GET /api/trpc/chat.onMessage?input={"room":"general"} as an EventSource. 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.

  5. onEvent appends each message to the list. The header shows connected, the hook status (starting until the server confirms the subscription, then listening) and extra.eventId of the last event.

  6. 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.

When to use it
  • 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 TrpcWebsocketAdapter and applyWSSHandler; the listeners stay the same.

Summary

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.