Overview
A stream delivers server-sent events; a channel is a WebSocket subscription, which the caller can also send on when it names .send(). Either one is served by the process that defines it with .implement(), or describes where another process serves it with .get(), .connect() or .via().
import { courier, defineGroup } from "@noverax/courier/define"
import { z } from "zod"
const { channel } = courier()
export const chat = defineGroup({
prefix: "chat",
endpoints: {
room: channel
.variables(z.object({ room: z.string(), nick: z.string() }))
.topic((v) => ({ room: v.room }))
.send(z.object({ text: z.string() }))
.response(z.object({ from: z.string(), text: z.string() }))
.implement((v) => ({
onJoin(ctx) {
ctx.send({ from: "server", text: `welcome to ${v.room}` })
},
onMessage(ctx, message) {
ctx.broadcast(ctx.topic, { from: v.nick, text: message.text })
},
})),
},
})A channel's onJoin runs once its subscription is set up and sent what it missed, and so does a channel's generator: the subscription has joined its topic by then, so a refusal thrown in either ends it only after the topic's events may have reached it. Check who may subscribe in the handler's authorize or in a middleware, which run before anything is sent; authorize runs again when renewed credentials change who the connection is. When the subscription ends — its client leaves it or subscribes again, its connection closes, or the channel closes it — ctx.signal fires and onLeave runs, once for each onJoin called: one that refused the join too, and one still running, which it does not wait for and whose ctx.send reaches no one now. A subscription its client leaves before it joins runs neither.
Serving a stream
A stream's .implement() takes an async generator, handed the subscription's variables, a signal that aborts when the client leaves, the lastEventId a reconnecting client resumes after, and the request's headers. Each event it yields is { data }, with an event name or an id where it needs them; tracked(id, data) gives the event an id, so a client that reconnects is handed only what it missed:
import { courier, defineGroup } from "@noverax/courier/define"
import { ForbiddenError } from "@noverax/courier/realtime"
import { tracked } from "@noverax/courier/realtime"
import { z } from "zod"
const { stream, channel } = courier()
export const orders = defineGroup({
prefix: "orders",
endpoints: {
updates: stream
.variables(z.object({ shop: z.string() }))
.response(z.object({ id: z.string(), state: z.string() }))
.implement(async function* (ctx) {
if (!(await canWatch(ctx.headers, ctx.variables.shop))) {
throw new ForbiddenError("Not a member of this shop")
}
for await (const order of orderChanges(ctx.variables.shop, ctx.lastEventId, ctx.signal)) {
yield tracked(order.id, order)
}
}),
// A channel nobody sends on is served the same way; it yields the values themselves
ticker: channel.response(z.number()).implement(async function* () {
yield 1
}),
},
})Returning ends the stream: the client stops reading and does not reconnect. Throwing fails it. A check like canWatch holds back a stream's events, which its generator yields, but not a channel's: its subscription has joined its topic before its generator runs, so who may subscribe to a channel is checked in authorize, as the overview says. A RealtimeError — ForbiddenError, AuthError, RateLimitError, RealtimeTimeoutError, or one built with its own code — reaches the client with its code and message; any other error reaches it as code 5000, "Stream failed", and in full only the server's log.
Reaching a stream or a channel
A stream or channel served with .implement() is reached through the server that serves it — the proxy routes of your framework adapter, or a standalone server — so a proxy caller opens it: createProxyCaller, or createProxyQueryCaller for the React hooks.
A stream is opened by asking for it, so through the proxy its variables travel in the address of the stream route — /api/sse?_s=api&_g=live&_m=feed&_v={…} — and every access log on the way writes them down. Keep what must not be written down, such as an email address, out of a stream's variables: the user's session carries who they are, and a header the source forwards carries the rest. A channel sends its variables in its subscription's first frame on the socket, never in an address.
A direct caller, createCaller or createQueryCaller, sends everything to the API's baseURL, which is the upstream's address. Nothing serves this process's streams and channels there, so calling one through a direct caller throws ConfigurationError("DIRECT_CALL_TO_SERVED_ENDPOINT"), naming it, when it is called — the React hooks report it through error — and the rest of the API stays callable. A stream or channel addressed with .get(), .connect() or .via() is another process's, and a direct caller opens it at baseURL.
A proxy caller reaches another process's stream or channel too: the proxy relays it, opening it where its definition says. A stream is opened with the source's headers, the request headers the proxy lets through, the user's session, and whatever the source's middleware sets. A browser reaches a third party's stream through its own server, with no CORS to configure and no key of its own to hold. A channel's upstream socket is opened with the same headers, as a direct caller in the server's process would open it; the subscriptions relayed with the same headers share it, so one user's channels share a socket and no two users' do. The proxy relays the streams and channels it would forward as endpoints: one no .expose() mark opens stays unreachable.
- A stream's events pass on as they came: ids, event names, and data that is not JSON as its text. A dropped upstream connection is reopened from the last event id, while the client's stays open. The client's
Last-Event-IDis sent upstream when it resumes. - The stream ends as the upstream's ends. It fails as the upstream's fails: a refusal carries the upstream's status as code
4000 + status, so a401arrives as4401. A client that leaves closes the upstream stream. - A channel's frames pass both ways, and it ends as its upstream subscription ends, with its code — a connection the upstream refuses included. A message the upstream subscription has no room to hold, while it joins or comes back, is answered with a
4429error on the channel, which goes on. Subscribers of the server with equal variables share one upstream subscription. - A path parameter that is empty,
.or..is refused before anything is sent, as it is for an HTTP call. Otherwise it would reach a route above the declared one with the server's credentials.
A channel or a stream is kept from clients until something marks it, as an HTTP endpoint is — .expose() on it, or expose on its group or its API — whether the server relays it or serves it itself with .implement(). A subscription to one nothing marks is answered as for a channel that does not exist (complete with 4403), and a stream as for an unknown one (400), so a client guessing names learns nothing. While developing, the server's log says which endpoint it refused and why, once for each.
Reading a subscription
Calling a stream, a push channel or a channel with .send() returns a subscription, and every kind reads the same way. A channel with .send() is the same object with send on it as well; on the others send does not exist, in the types or at run time.
const ticks = client.prices.ticks({ symbol: "ACME" }) // a stream or a push channel
ticks.on("data", (tick) => render(tick))
const room = client.chat.room({ room: "general", nick: "ada" }) // a channel with .send()
room.on("data", (message) => append(message))
room.send({ text: "hello" })for await reads it too: each event comes with its data and, from a stream, its id and event name. The loop ends as the subscription ends, and leaving it early closes the subscription:
for await (const event of client.orders.updates({ shop: "north" })) {
render(event.data)
}What arrives before anything reads it — between the call and the first listener, or the loop — is kept for the first reader, up to a thousand events; past that the oldest are dropped, and dropped counts them. Once a listener reads, nothing is kept for later.
A subscription has five events. Listening to any other is a type error, and throws ConfigurationError UNKNOWN_EVENT.
| Event | Hears | Each time |
|---|---|---|
data | the data, and the event it came in | it delivers something |
error | a RealtimeError | the server refuses a message, a handler fails or a message is dropped from a full queue — the subscription goes on — and once more when it ends with an error |
status | connecting, connected, reconnecting or disconnected | its status changes |
open | { first, resumed } | it is open: the first time, again after each reconnect, and when the server says what it holds may be stale |
close | { reason }: closed, completed, or failed with its error | it ends |
A subscription is connecting from the moment it is made, and connected once the server runs it: a channel once the server has confirmed its subscription, not as soon as its socket opens. A listener that throws is logged, and the others still hear the event.
A channel or a push subscription made again after a drop tells the server the last event of its topic it counted, and resumed: true says the server sent every event it missed — the server keeps them for that only where the channel's handler has a history, or the server a Redis log: nothing needs reading again. open with first: false and resumed: false means what it missed may not have been sent — the server could not, or the topic's sequence broke while it ran: read what it shows again. A client that reads too slowly loses a topic's events for as long as its socket's buffer holds more than the server's maxBufferedAmount, 1 MB by default: what it is told of its subscriptions still reaches it, and an event lost breaks the sequence, or, as the subscription resumes, makes resumed false. A stream hears resumed: false after every reconnect.
reconnect() connects again at once. On a subscription that is open or waiting to reconnect, the socket or the stream's connection is opened anew, with its credentials asked for again; the channels of one caller share a socket, so all of them reconnect. A subscription the server ended opens again, its listeners kept — a loop that ended does not resume, a new one reads it. One the application closed stays closed: call the endpoint again. close() ends it for good.
How a subscription ends
A subscription ends in one of three ways, and the client can tell them apart.
- The client closes it —
close(), a loop left early, or a React hook unmounting.closesaysclosed. - The server finishes it — a stream's generator returned, or a channel closed itself. A loop leaves;
closesayscompleted. It does not reconnect. - The server fails it — the handler threw, the subscription or the join was refused, its variables failed their schema, or a limit was reached. The
errorevent hears theRealtimeErrorwith the code and message the server sent, the status becomesdisconnected, andclosesaysfailed; a loop rejects with the same error. A stream refused with a status no retry would change — a4xxother than408and429, or a redirect it does not follow, as one to another origin — arrives as code4000 + status, so a401is4401and a302is4302, and is not reconnected — a401aside, which is tried once more when the credentials asked for anew have changed; a408, a429and a5xxare retried as a dropped connection is, no sooner than theRetry-Afterthe server sent.
A dropped connection is none of these: the client reconnects, resumes a stream after the last event id it saw, and subscribes its channels again — see Staying connected. When it has spent its retries, it fails with a ConnectionError.
import { isRealtimeError } from "@noverax/courier/realtime"
const updates = client.orders.updates({ shop: "north" })
try {
for await (const event of updates) render(event.data)
// the server finished the stream
} catch (error) {
if (isRealtimeError(error) && error.code === 4403) showNoAccess(error.message)
else throw error
}
const room = client.chat.room({ room: "general", nick: "ada" })
room.on("error", (error) => notify(error.message)) // a refused message: the channel goes on
room.on("status", (status) => setOnline(status === "connected"))
room.on("close", (info) => {
if (info.reason === "failed" && info.error.code === 4401) signInAgain().then(() => room.reconnect())
})A channel's error event also reports what it refused without ending: a message that failed its schema (4422), one larger than the server accepts (4413), or an onMessage that threw. send() returns whether the message went out or waits for the channel; false means it was dropped, with a warning.
Topics
Every subscription to a channel is on a topic: the endpoint, source.group.method, qualified by a key. ctx.topic is the subscriber's own, and ctx.broadcast(topic, data) sends to every other subscriber on it — every replica's, with a pubsub adapter.
Without .topic(), the key is all of a subscriber's variables: subscribers share a topic only when their variables are equal. That is the safe default for a feed whose variables pick what it shows, but it splits a room into as many topics as it has members as soon as a variable belongs to one member — a nickname, a cursor colour.
.topic() names what subscribers share a topic by. It reads the variables as the schema produced them, and returns what JSON can carry. In the channel above, everyone in room r1 is on one topic, so a broadcast reaches all of them, while each keeps its own nick in v and ctx.variables. A key that throws ends that subscription with code 5000.
On one connection, subscriptions whose key is equal are one subscription. Channels of one caller called with equal variables share it: the first one's subscribe opens it and the server runs it once, so a channel called once it runs hears what is sent from then on, not the snapshot onJoin or the generator sent before. Keep what a channel shows where every component that shows it reads it, or read the snapshot with a query. Channels whose variables differ but whose key is equal subscribe each: the newer subscribe replaces the older, whose onLeave runs, both channels receive what is sent on the topic, and after a reconnect the subscription is made again with the newer one's variables. Two browsers, or two tabs, are two connections.
.topic() is named before .implement(). A channel another process serves has its topics decided there, so naming it before .connect() or .via() throws ConfigurationError("TOPIC_ON_REMOTE_CHANNEL").
How a topic reads
The key is canonical JSON — api.chat.room#{"room":"r1"} — so every distinct key is a topic of its own. qualifyTopic from @noverax/courier/realtime builds a topic for broadcastToTopic on the server's connection registry.
What a channel sends
A stream's events, a push channel's values and what a channel's handlers pass to ctx.send() and ctx.broadcast() are held to the endpoint's .response() schema before they leave the server, and the client receives the schema's output — defaults filled in, transforms applied. A channel's ctx.send() or ctx.broadcast() of a value that does not match throws a RealtimeValidationError where it was called and sends nothing; a channel's response schema must validate synchronously. Validation has the details.
Message size
A server accepts messages up to its maxMessageSize, 64 KB by default, and answers a larger one with a 4413 error on a connection that stays open. The client does not send one: the server names its maxMessageSize when it admits the socket, and a channel's send of a message whose encoded frame is longer — longer than 64 KB, until a server has named its own — puts nothing on the wire: send answers false, and the channel's error event reads code 4413. The channel and everything else on the socket go on.
A server whose WebSocket layer closes the socket over a frame too large to read, with close code 1009, loses that one message only: the client reconnects, and each channel on the socket hears a 1009 error.
Connections
A caller's channels and push subscriptions share one socket on each URL, which the caller's ws options open. Realtime Connections says what those options are, how a socket and a stream come back after a dropped network, a hidden page or a restarted server, what each close code means, how a connection goes on where no WebSocket gets through, and who the server takes a connection to be.
Next steps
- React: Streams & Channels — follow a stream, keep a query up to date, and send on a channel from components
- Standalone Server — serve streams and channels from their own process
- Redis Adapters — broadcast across replicas, resume streams, track presence