Subscription Procedures with Event Types
What you'll learn: How to type tRPC subscription procedures to ensure type-safe real-time events flowing from server to client over WebSockets.
What Are Subscription Procedures?
Unlike queries and mutations that complete immediately, subscription procedures establish long-lived connections that push events from server to client in real-time. Think of them like a radio station broadcast—once you tune in, you receive a continuous stream of updates until you disconnect.
In tRPC, subscriptions use WebSocket connections to maintain this persistent channel. The challenge is ensuring both the event data shape and the event types themselves are fully type-safe across the network boundary.
Typing Subscription Events
When creating a subscription, you define what events can flow through the connection. Each event needs a well-typed payload:
// Server-side subscription procedure
subscription: t.procedure
.input(z.object({
channelId: z.string()
}))
.subscription(({ input }) => {
return observable<{
type: 'message';
data: { text: string; userId: string; timestamp: number };
} | {
type: 'userJoined';
data: { userId: string; username: string };
} | {
type: 'userLeft';
data: { userId: string };
}>((emit) => {
// Emit events through the connection
const handleMessage = (msg: string) => {
emit.next({
type: 'message',
data: { text: msg, userId: '123', timestamp: Date.now() }
});
};
return () => {
// Cleanup logic
};
});
})
The client automatically infers a discriminated union of all possible event types. Each event's type property acts as the discriminant, letting you narrow to the exact payload shape in your handlers.
Why This Matters
Without proper typing, real-time events become a wild west of any types. You'd have no autocomplete for event payloads, no protection against typos in event names, and runtime errors when the server sends data your client doesn't expect. By typing the observable's emission type as a discriminated union, TypeScript enforces that every event matches your contract—before any data crosses the wire.
Key Takeaway: Type subscription procedures with discriminated unions for their event emissions, giving you compile-time safety for real-time WebSocket data streams between server and client.