Skip to content

Server and client

createHandler, createClient, errors, context, cancellation and the HTTP protocol.

import { createHandler } from 'ts-bin-rpc/server';
import { serverProcedures } from './tbr.gen.ts';
const handler = createHandler(appRouter, {
procedures: serverProcedures,
prefix: '/rpc',
context: async (req) => ({ user: await auth(req) }),
});

handler is (request: Request) => Promise<Response>. It runs anywhere the Fetch API does: Bun.serve({ fetch: handler }), Deno.serve(handler), export default { fetch: handler } in Workers. For node:http, wrap it:

import http from 'node:http';
import { toNodeListener } from 'ts-bin-rpc/node';
http.createServer(toNodeListener(handler)).listen(3000);

toNodeListener streams the body into the Request and keeps every Set-Cookie of the response. Its maxBytes (64 MB) is a second fence; the handler’s own limits.maxBytes decides.

The handler compares the router with the generated table at startup. A procedure that exists on one side only throws an error that tells you to run tbr generate.

OptionDefault
procedures—serverProcedures from the generated file (procedures works too)
prefix/path prefix of every procedure
context—(request) => ctx, once per request to a procedure that takes ctx; may be async and may throw RpcError. Required by the types when a procedure takes ctx
schemaMismatch'warn'the client was generated from another contract version: 'warn' logs once per procedure, 'error' answers 409, 'ignore'
limits1 MB, depth 64, 16M elements{ maxBytes, maxDepth, maxNodes } for request bodies and inputs. A body over maxBytes gets 413 as it arrives. A message also gets at most a few elements per byte, so a small body cannot claim millions of objects
onErrorconsole.error(error, { path, request }) for errors other than RpcError
checks, refine—validation
batch{ maxCalls: 64 }batches; false refuses them
socket—{ allowedOrigins, maxSubscriptions, maxCalls } of WebSocket connections

The second parameter of every procedure is the context, and its type comes from the procedures. If context throws an RpcError, for example UNAUTHORIZED, the client gets that error and the procedure does not run.

context runs only for procedures that declare ctx, directly or through middleware that needs it: tbr generate marks them in serverProcedures. A public ping does not pay for a session lookup. Keep context cheap anyway, and do the expensive part where it is needed:

context: (request) => ({ request, db }), // no I/O here
const authed = middleware(async ({ ctx }: Call<{ request: Request; db: Db }>) => {
const user = await ctx.db.session(ctx.request.headers.get('cookie'));
if (!user) throw new RpcError('UNAUTHORIZED', 'sign in first');
return { ...ctx, user };
});

See Middleware.

import { createClient } from 'ts-bin-rpc/client';
import type { AppRouter } from '../server/router.ts';
import { clientProcedures } from '../server/tbr.gen.ts';
export const api = createClient<AppRouter>({
url: '/rpc',
procedures: clientProcedures,
headers: () => ({ authorization: `Bearer ${token()}` }),
});
OptionDefault
url—base URL: /rpc or https://api.example.com/rpc
procedures—clientProcedures from the generated file
headers—sent with every call; a function is called before each one
fetchglobalThis.fetchfor tests, retries or instrumentation
decode'lazy''eager' returns plain objects instead of views; a map like { 'user.get': 'eager' } sets it per procedure
verifysee viewsverify responses before reading them: always in development, in production only when the response does not show the server has the same contract
limitsas on the serverlimits for verifying responses
debugfalselog every call to the console
batch—batch(): calls of one task in one request (batching)
socket—webSocket(url): subscriptions, and calls if asked, over one socket (WebSocket)

Every procedure takes the input, if it has one, and then call options:

const abort = new AbortController();
const user = await api.user.get({ id: 1 }, { signal: abort.signal, headers: { 'x-trace': id } });
const me = await api.whoami({ signal: abort.signal }); // no input: options come first
const copy = await api.user.get({ id: 1 }, { decode: 'eager' }); // plain objects for this call

The DevTools extension lists calls and streams with their inputs and decoded responses.

debug: true logs one collapsed group per call: the procedure, status, time and sizes, followed by the input and the output as plain objects. It also warns when the server’s contract hash differs from the client’s.

▸ tbr user.get 200 3.1 ms, 12 B → 214 B

To look at a body captured from the Network tab, save it and decode it:

Terminal window
pnpm exec tbr decode response.bin --proc user.get # the output of user.get
pnpm exec tbr decode request.bin --proc user.get --input # its input

Throw RpcError from a procedure, or from context, to send an error to the client. The client throws an RpcError with the same code, message and data:

// server
throw new RpcError('NOT_FOUND', `no user ${input.id}`, { id: input.id });
// client
try {
await api.user.get({ id: 99 });
} catch (e) {
if (e instanceof RpcError && e.code === 'NOT_FOUND') showNotFound(e.data);
}

data travels as JSON; bigints in it arrive as decimal strings, and data that is not JSON (a cycle) is dropped. Any other exception reaches onError; the client gets 500 INTERNAL without details.

CodeStatusRaised by
BAD_INPUT400the server: input failed verification or a rule, or is missing; data is an InputIssue
UNAUTHORIZED401your code
FORBIDDEN403your code
NOT_FOUND404your code, or the server: no such procedure
METHOD_NOT_ALLOWED405the server: not a POST, or not a GET or POST for a query
CONFLICT409your code
SCHEMA_MISMATCH409the server, with schemaMismatch: 'error'
PAYLOAD_TOO_LARGE413the server: over limits.maxBytes, or a batch over maxCalls
UNSUPPORTED_MEDIA_TYPE415the server: wrong content type
TOO_MANY_REQUESTS429your code, or the server: over a socket’s maxSubscriptions or maxCalls
SLOW_CONSUMER429the server: a stream’s client read slower than it produced
INTERNAL500the server: a procedure threw something else
BAD_OUTPUT500the server: a procedure returned a value that does not match its type
BAD_RESPONSE502the client: the response is not a valid ts-bin-rpc message
UNAVAILABLE503a proxy, or the server going away
TIMEOUT504a proxy
DISCONNECTED0the client: the request failed or the connection broke

These codes are ts-bin-rpc’s: do not reuse them for other meanings. Codes not in the table are yours, and default to status 400. Pass { status } as the fourth argument to choose another: new RpcError('PAYMENT_REQUIRED', '…', undefined, { status: 402 }); a status outside 400–599 goes out as 500. A response that is not ts-bin-rpc’s, such as a proxy’s 503 page, gets the code of its status from the table.

Everything a call rejects with is an RpcError, transport failures included: a failed fetch, a closed socket or a broken batch response is DISCONNECTED or BAD_RESPONSE. The one exception is an abort: the call rejects with the signal’s reason, as fetch does. Errors thrown by your own headers function come through as they are.

BAD_OUTPUT means a bug on the server, so the client gets no details. onError gets the EncodeError with the path to the bad value, and the default handler prints it:

ts-bin-rpc: procedure 'user.list' returned an invalid value at [17].manager.age: expected u8, got 300
  • A call is POST {prefix}/{procedure path} with the encoded input as the body. A procedure without input sends an empty body. A query is a GET with the input in the URL.
  • Requests and responses use content-type: application/vnd.tbr. The server refuses anything else with 415. Browsers cannot send this content type from a form or a “simple” cross-origin request, which protects against CSRF.
  • A stream procedure answers with content-type: application/vnd.tbr.stream, a sequence of frames over one response; see Streams. A batch uses application/vnd.tbr.batch. The three are exported as CONTENT_TYPE, STREAM_CONTENT_TYPE and BATCH_CONTENT_TYPE from ts-bin-rpc, for proxy and compression settings.
  • Errors are a fixed envelope with a flag in the header, so the client reads them without knowing the procedure.
  • The x-tbr-schema header carries a hash of the procedure’s contract in both directions. The hash covers the lockfile entries of every type the procedure reaches. When client and server differ, the server warns by default. Safe changes stay compatible, and old clients during a deploy are normal.

The byte layout is specified in FORMAT.md (in Russian).