Catalog My learning Blog
tRPC Course: Type-Safe APIs with TypeScript and React · Phase 4 · Lesson 11 · 6 min read

tRPC Subscriptions over Server-Sent Events (SSE)

On this page
  1. When you need a subscription
  2. Write a subscription as an async generator
  3. Connect from the client
  4. Authenticate an EventSource
  5. Survive dropped connections
  6. Scale past one server
  7. Check yourself

When you need a subscription

Queries answer "what is the data now?". Some screens need "tell me when it changes": a task board shared by a team, a build log, a chat, a progress bar for a long job. Polling every few seconds works but wastes requests and still lags. A subscription keeps a connection open and the server pushes each update.

tRPC 11 supports two transports for subscriptions:

  • Server-Sent Events (SSE), a plain HTTP response that stays open and streams events one way, from server to client. It works through most proxies and load balancers, and browsers reconnect automatically.
  • WebSockets, a two-way connection, which needs a separate WebSocket server and more care with infrastructure.

For server-to-client updates, which is what most apps need, the tRPC docs recommend SSE, and this lesson uses it. The client sends its own changes with normal mutations.

Write a subscription as an async generator

A subscription procedure is an async function* that yields each event. Here TaskBoard announces new tasks to their owner:

JavaScript
import { EventEmitter, on } from 'node:events';
import { tracked } from '@trpc/server';

const events = new EventEmitter();

export const taskRouter = router({
  create: protectedProcedure.input(CreateTask).mutation(({ ctx, input }) => {
    const task = saveTask(ctx.user.id, input);
    events.emit('created', task);
    return task;
  }),

  onCreated: protectedProcedure
    .input(z.object({ lastEventId: z.string().nullish() }).optional())
    .subscription(async function* ({ ctx, input, signal }) {
      // 1. on reconnect, replay what the client missed
      if (input?.lastEventId) {
        for (const task of tasksCreatedAfter(ctx.user.id, input.lastEventId)) {
          yield tracked(task.id, task);
        }
      }
      // 2. then stream new events until the client goes away
      for await (const [task] of on(events, 'created', { signal })) {
        if (task.ownerId === ctx.user.id) yield tracked(task.id, task);
      }
    }),
});

Three details make this robust:

  • signal is aborted when the client disconnects. Passing it to on() ends the loop, so you don't leak listeners.
  • tracked(id, data) attaches an event id. The browser remembers the last id it received.
  • lastEventId is filled in by tRPC when the client reconnects, so the generator can replay anything missed while the connection was down.

The filter on ownerId matters as much as it did on Day 4. A subscription is a long-lived query, and it needs the same authorization checks.

Connect from the client

Route subscriptions to httpSubscriptionLink with splitLink, as you saw on Day 8:

TypeScript
const trpcClient = createTRPCClient<AppRouter>({
  links: [
    splitLink({
      condition: (op) => op.type === 'subscription',
      true: httpSubscriptionLink({ url: '/trpc', transformer: superjson }),
      false: httpBatchLink({ url: '/trpc', transformer: superjson }),
    }),
  ],
});

In React, use useSubscription from the tRPC integration, with subscriptionOptions:

TypeScript
import { useSubscription } from '@trpc/tanstack-react-query';

function LiveTasks() {
  const trpc = useTRPC();
  const queryClient = useQueryClient();

  const sub = useSubscription(trpc.task.onCreated.subscriptionOptions(undefined, {
    onData: () => queryClient.invalidateQueries({ queryKey: trpc.task.list.queryKey() }),
  }));

  return <p>Live: {sub.status}</p>;   // 'connecting', 'pending' (open, waiting), or 'error'
}

Invalidating the list when an event arrives is the simplest pattern: the subscription says *something changed*, and the normal query fetches the truth. With two browser tabs open in testing, a task created in the second tab appeared in the first one's subscription within a moment.

Authenticate an EventSource

Browsers' EventSource can't send custom headers, so a Bearer token in Authorization doesn't work. You have two good options:

  • Cookies. If the API is on the same origin, the browser sends its session cookie with the SSE request automatically. This is the cleanest option and fits a BFF.
  • connectionParams. The link can send extra values with the connection, which the server reads in createContext:
JavaScript
// client
httpSubscriptionLink({ url: '/trpc', transformer: superjson, connectionParams: async () => ({ token: await getToken() }) }),

// server
createContext: ({ req, info }) => {
  const token = info.connectionParams?.token ?? readBearer(req.headers);
  return { user: token ? verifyToken(token) : null };
},

connectionParams travel in the URL's query string, where they can end up in access logs. Prefer short-lived tokens, or use cookies when you can.

Survive dropped connections

Connections drop: phones change networks, laptops sleep, proxies cut idle streams. Three server settings in initTRPC.create help:

TypeScript
const t = initTRPC.context<Context>().create({
  transformer: superjson,
  sse: {
    ping: { enabled: true, intervalMs: 15_000 },          // keeps idle proxies from closing the stream
    maxDurationMs: 5 * 60_000,                             // end each stream after 5 minutes
    client: { reconnectAfterInactivityMs: 30_000 },        // client reconnects if nothing arrives
  },
});

Ending streams on purpose with maxDurationMs sounds odd, but it suits serverless platforms with request time limits, and it spreads reconnects across server instances during a deploy.

A test with a 1.5-second maximum showed the replay at work. Events a and b arrived, the stream ended, event c was published while the client was disconnected, and the client reconnected on its own:

Code
connect #1 lastEventId=null
connect #2 lastEventId=2
received: 1:a 2:b 3:c

Because the second connection carried lastEventId=2, the generator replayed c. Without tracked and the replay step, c would have been lost silently.

Scale past one server

The EventEmitter above only works inside one Node process. With two server instances behind a load balancer, a task created on instance A never reaches a subscriber connected to instance B. In production, publish events through a shared broker, such as Redis pub/sub, Postgres LISTEN/NOTIFY, or a message bus, and have each instance subscribe to it.

Replay also needs a durable source. An in-memory list disappears on restart, so read missed events from the database (for example, tasks with an id greater than lastEventId) or from a stream that keeps history, like Redis Streams.

TipEach open SSE connection holds a request open. Check your proxy's and platform's limits on concurrent connections and response time, and set maxDurationMs below the platform's timeout.

Check yourself

The signal is aborted when the client disconnects, which ends the for await loop and removes the event listener, so disconnected clients don't leak listeners.

Each event gets an id, the client reports the last id it saw when reconnecting, and the generator can replay everything after it, so events published during a disconnect aren't lost.

Events only reach subscribers connected to the instance that emitted them, so most users miss most updates. Publish events through a shared broker such as Redis pub/sub, Postgres LISTEN/NOTIFY or a message bus, and have every instance subscribe to it. Replay also needs a durable source, because in-memory history disappears on restart.

The browser's EventSource, which carries Server-Sent Events, can't set custom headers. Use the session cookie, which is sent automatically on same-origin requests, or connectionParams, which tRPC sends in the query string and exposes in createContext. Since the query string can end up in logs, prefer cookies or short-lived tokens.

Set sse.maxDurationMs below the platform limit so tRPC ends streams cleanly before they're killed, and let the client reconnect with lastEventId to replay anything missed. Turn on sse.ping so idle proxies don't close quiet streams, and reconnectAfterInactivityMs so a dead connection is noticed.