Views
How responses are read lazily, and the few places where a view is not a plain object.
The client does not parse a response into objects. It checks the bytes once, then returns views: objects whose getters read fields from the response buffer when you touch them. Strings decode on first read; a field you never read costs nothing.
const users = await api.user.list();users.length; // a real Arrayusers.filter((u) => u.role === 'admin').map((u) => u.name); // reads two columns, nothing elseIn most code a view behaves like the plain object its type describes. This page lists where it doesn’t.
What works as usual
Section titled “What works as usual”- Property reads, destructuring,
in, optional chaining:const { id, name } = user. - Arrays are real arrays:
Array.isArray,map,filter,sort, spread of the array itself ([...users]). JSON.stringify(view)gives the same JSON as for the plain object. Views implementtoJSON.console.log(view)in Node prints the plain value.- Discriminated unions narrow:
switch (shape.kind). - Repeated reads return the same nested object:
users[0] === users[0],user.tags === user.tags.
What does not
Section titled “What does not”setUser({ ...user, name: 'Ada' }); // wrong: loses every fieldsetUser({ ...toPlain(user), name: 'Ada' }); // rightIf a procedure’s results always go to such code, ask the client for plain objects instead.
- Views are read-only. Assigning a field throws a
TypeErrorin strict mode, which is all ES modules. To edit, copy withtoPlainfirst. structuredClone,postMessage, IndexedDB and React Server Components copy own data properties, so they get{}instead of the fields. PasstoPlain(view)instead.- Don’t rely on the identity of
Datevalues. In arrays of objects each read returns a newDate. Compare withgetTime().
Plain objects
Section titled “Plain objects”toPlain turns a view into plain data:
import { toPlain } from 'ts-bin-rpc';
const plain = toPlain(user); // User, made of plain objects, arrays, fresh Dates and typed array copiestoPlain makes a deep copy: it reads every field once and copies typed arrays. Use it at the edge
of code that needs plain data: state stores, workers, caches, mutations.
When a procedure’s results always end up there, let the client do it. decode: 'eager' returns
what toPlain would, for the whole client, per procedure or per call:
const api = createClient<AppRouter>({ url: '/rpc', procedures: clientProcedures, decode: 'eager' });
createClient<AppRouter>({ url: '/rpc', procedures: clientProcedures, decode: { 'user.get': 'eager' } });
await api.user.list({ role: 'admin' }, { decode: 'lazy' }); // this call returns viewsA call option wins over the procedure’s entry, which wins over the client-wide mode. The default
is 'lazy'. The map’s keys are checked against the router, so a typo in a path is a type error.
Eager results are copies with nothing tied to the response buffer. The price is laziness: every field is read, even the ones you never touch. See Performance.
Typed arrays share the response
Section titled “Typed arrays share the response”A Float32Array field is a view over the response buffer, which is why reading it is free. It is
a read-only property created with the view, not a getter, so a loop like
for (let i = 0; i < s.t.length; i++) sum += s.t[i] runs as fast as over a plain object. Two
consequences of sharing the buffer:
- Writing into it changes the response. Fine if that’s what you want; otherwise
slice()it. - It keeps the whole response alive. If you keep one small typed array from a large response,
the whole buffer stays in memory.
slice()what you keep long-term.
Verification
Section titled “Verification”Before the first view is returned, the whole message is checked:
- offsets and lengths stay inside the buffer;
- strings are valid;
- enum indexes and union tags exist;
- required fields are present;
- nesting depth and the total number of elements stay within limits, so a message built with reused offsets cannot make a reader loop.
After that, reads do no bounds checks.
The server always verifies inputs. The client verifies every response in development. In
production builds, where process.env.NODE_ENV is 'production', it skips verification only for
a response that shows the server has the client’s version of the procedure: an HTTP response whose
x-tbr-schema header equals the client’s hash. A tab left open across a deploy, a cache or a proxy
that serves another version, and every response over a WebSocket or in a batch (they carry no hash)
are verified. Bundlers such as Vite, webpack and esbuild with define replace that expression at
build time; without a bundler the client is in development mode. Set verify in createClient to
choose explicitly:
createClient<AppRouter>({ url: '/rpc', procedures, verify: true }); // a server you do not controlA cross-origin client sees x-tbr-schema only if the server exposes it
(Access-Control-Expose-Headers: x-tbr-schema); otherwise it verifies every response.
A message that fails verification is a 400 BAD_INPUT on the server and a BAD_RESPONSE error on
the client.
On the server
Section titled “On the server”Inputs arrive as plain objects, not views. They are verified, then decoded in full: inputs are usually small, and handlers often change what they receive. Outputs are encoded from whatever your procedure returns, plain objects or views alike.