Skip to main content

oRPC event iterators

A job runner. Each button starts a job with a regular oRPC call, and every job card streams its progress from an oRPC event iterator: an async generator on the server that yields one event per step and then returns. Start a few jobs at once to see the streams run side by side.

advancedorpcstreaminguseListenerrealtime
import { useListener, useSubmit } from "@hyper-fetch/react";
import { useState } from "react";

import { realtime, sdk } from "./api";

type Job = { id: string; steps: number };

const JobCard = ({ job }: { job: Job }) => {
const [log, setLog] = useState<string[]>([]);
// The payload is the procedure input. Each job is its own stream.
const { data, extra, status, error, onEvent } = useListener(
realtime.job.onProgress.$listener.setPayload({ id: job.id }),
);

onEvent(({ data: event }) => {
// `at` is a Date: the oRPC serializer keeps rich types in every event.
setLog((current) => [`${event.at.toLocaleTimeString()} ${event.stage}`, ...current].slice(0, 4));
});

return (
<article>
<header className="toolbar">
<strong>{job.id}</strong>
<small className="muted" aria-busy={status === "starting"}>
{status} / event {extra?.id ?? "-"}
</small>
</header>
<progress value={data?.step ?? 0} max={job.steps} />
{status === "ended" && <p>Done in {job.steps} steps.</p>}
{status === "failed" && <p className="error">{error?.message}</p>}
<ul className="log">
{log.map((line) => (
<li key={line}>{line}</li>
))}
</ul>
</article>
);
};

export const App = () => {
const [jobs, setJobs] = useState<Job[]>([]);
const { submit, submitting, error } = useSubmit(sdk.job.start.$mutation);

const start = async (steps: number) => {
const { data } = await submit({ payload: { steps } });
if (data) setJobs((current) => [data, ...current]);
};

return (
<main className="container">
<hgroup>
<h1>oRPC event iterators</h1>
<p>Each job streams its progress from an async generator on the server into useListener.</p>
</hgroup>
<div role="group">
{[4, 8, 12].map((steps) => (
<button key={steps} type="button" aria-busy={submitting} disabled={submitting} onClick={() => start(steps)}>
Start a {steps}-step job
</button>
))}
</div>
{error && <p className="error">Could not start the job: {error.message}</p>}
{jobs.length === 0 && <p className="muted">Start a job, or a few at once.</p>}
<div className="grid-2">
{jobs.map((job) => (
<JobCard key={job.id} job={job} />
))}
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/orpc/event-iterator hyper-fetch-orpc-event-iterator && cd hyper-fetch-orpc-event-iterator && npm install && npm run dev
What it shows
  1. OrpcStreamAdapter connects a HyperFetch Socket to oRPC event iterator procedures over an HTTP event stream.
  2. OrpcSocketSchema<typeof router> turns every event iterator into a typed $listener.
  3. useListener status follows the stream: starting, listening, and ended when the generator returns.
  4. Event meta: withEventMeta(event, { id }) on the server becomes extra.id on the client.
  5. Rich types in events: at is a Date in every event, encoded by the oRPC serializer.

How it works​

  1. server/router.ts has two procedures. job.start is a regular procedure that returns { id, steps }. job.onProgress uses an async generator as its handler, which makes it an event iterator: each yield sends one event, and the end of the function ends the stream.

  2. Every event is wrapped in withEventMeta(event, { id: String(step) }). After a reconnect the adapter sends that id back, oRPC passes it to the handler as lastEventId, and the loop continues from the next step.

  3. server/app.ts mounts the router with the fetch RPCHandler in Hono. The same handler answers the regular call and the event stream.

  4. src/api.ts creates a client with OrpcAdapter() for job.start and a socket with OrpcStreamAdapter() for job.onProgress. OrpcSchema leaves event iterators out and OrpcSocketSchema keeps only them, so each SDK shows only what its transport can call.

    export const socket = new Socket({ url, adapter: OrpcStreamAdapter() });
    export const realtime = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, {
    camelCaseToKebabCase: false,
    });
  5. App starts a job with useSubmit(sdk.job.start.$mutation) and renders a JobCard for it. The card calls useListener(realtime.job.onProgress.$listener.setPayload({ id: job.id })), which sends POST /api/rpc/job/onProgress and reads the text/event-stream answer.

  6. data holds the latest event, so <progress value={data?.step}> moves with the stream. onEvent keeps a short log, formatting event.at with toLocaleTimeString() because it is already a Date. When the generator returns, status becomes ended and the card shows "Done".

When to use it
  • Progress of long jobs: builds, imports, exports, AI responses.
  • Live data on an oRPC API that already runs over HTTP, behind proxies or in serverless functions.
  • For many streams per client over one connection, switch the socket to OrpcWebsocketAdapter with the WebSocket RPCHandler; the listeners stay the same.

Summary

An async generator on the oRPC server is a stream of typed events. OrpcStreamAdapter and OrpcSocketSchema turn it into a listener, and useListener shows each event, the event id and the end of the stream.