Binary mode

Send values as Uint8Array chunks with binary.serialize, and decode them without running code with binary.deserialize.

Binary mode encodes a value as Uint8Array chunks instead of a string or a JSON tree. It streams like crossSerializeStream, and its decoder runs no code, like fromJSON. It is exported from seroval/binary:

JavaScript
import * as binary from 'seroval/binary';

Importing only serialize or only deserialize keeps the other half out of your bundle:

JavaScript
import { deserialize } from 'seroval/binary';

When to use it

Binary mode combines parts of the other modes:

  • Like the streaming functions, it sends the synchronous part of the value right away, then one chunk for each promise result and stream event.
  • Like the JSON functions, decoding validates the input and never evaluates it. It is built for input you do not trust.
  • Unlike both, the output is bytes. Strings are sent as UTF-8, or as UTF-16 when they hold a lone surrogate, and ArrayBuffer contents as raw bytes, with no base64 step.

It also has limits:

  • The receiver needs binary.deserialize. The output cannot run in a <script> tag.
  • There is no one-shot form. binary.serialize always reports its output through callbacks, even for a value with no promises.

Use it when the transport carries bytes, such as a fetch body, a ReadableStream or a WebSocket, and the receiver must not evaluate what it gets. See Choosing a mode for the full comparison.

A complete example

The sender turns a value into a ReadableStream of bytes. The receiver reads the bytes back into a value.

JavaScript
import * as binary from 'seroval/binary';

function toByteStream(value) {
  return new ReadableStream({
    start(controller) {
      binary.serialize(value, {
        refs: new Map(),
        onSerialize(bytes) {
          controller.enqueue(bytes);
        },
        onDone() {
          controller.close();
        },
        onError(error) {
          controller.error(error);
        },
      });
    },
  });
}

async function fromByteStream(stream) {
  const reader = stream.getReader();
  const { value } = await binary.deserialize({
    async read() {
      const result = await reader.read();
      // `undefined` once the stream ends.
      return result.value;
    },
    onError(error) {
      console.error(error);
    },
  });
  return value;
}

Send a value with a cycle and a promise:

JavaScript
// The sender
const user = { name: 'Ada', joined: new Date('2026-01-01') };
user.self = user;

const response = new Response(
  toByteStream({
    user,
    posts: fetchPosts(),
  }),
);

// The receiver
const value = await fromByteStream(response.body);

value.user.self === value.user; // true
await value.posts; // ['Hello', 'World']

The first chunk holds the object and a pending promise. fromByteStream returns as soon as that chunk is decoded. A second chunk settles posts once fetchPosts() resolves.

Serializing

binary.serialize(value, options) takes:

OptionTypeDefaultDescription
refsMaprequiredThe values already sent. Pass a new Map for each payload, or share one to send references between payloads.
onSerialize(bytes)functionrequiredReceives each Uint8Array chunk. It may return a promise, see Live streams. If it throws or its promise rejects, the error goes to onError and serialization stops.
onDone()functionrequiredRuns once every promise and stream has settled.
onError(error)functionrequiredRuns when a value cannot be serialized.
pluginsPlugin[]nonePlugins for extra types. Each one needs a binary section.
disabledFeaturesnumber0Feature flags to turn off, combined with |.
featuresnumberall featuresThe features to turn on, as a bit mask. Overrides disabledFeatures.
depthLimitnumber64Maximum nesting depth.
compactArrayBufferViewsbooleanfalseSend each view with a copy of its own bytes at offset 0, instead of its whole ArrayBuffer. Views then stop sharing a buffer.

The synchronous part of the value is sent as one chunk, before binary.serialize returns. Each settled promise and each stream event is sent as one more chunk. A value with no promises or streams calls onDone before binary.serialize returns.

By default, a view is sent with its whole ArrayBuffer and its offset, so views that share a buffer still share it after decoding.

Stopping

binary.serialize returns a function that stops serialization. Call it when the receiver goes away.

JavaScript
const stop = binary.serialize(value, options);

request.signal.addEventListener('abort', () => stop());

Stopping:

  • unsubscribes from streams, cancels live streams and returns async iterators;
  • runs the cleanups that plugins registered;
  • sends no more chunks and does not call onDone.

If a cleanup throws, the first error goes to onError. Calling the function again does nothing.

When serialization fails

onError receives the error itself, for example a SerovalUnsupportedTypeError. Binary mode does not wrap it in a SerovalParserError. A seroval error has a path to the part of the value that failed. For a value that a promise or stream sends later, the path starts at that value. An error that your code threw, such as from a getter, reaches onError unchanged and has no path. A seroval error that cannot take a path, because it is frozen or already has a path that is not an array, is wrapped in a SerovalParserError that has the path, with the original as cause.

  • The root value fails. For example, it contains a function. The bytes written so far are still sent, but they have no root, so the receiver rejects them. Sources that already started are stopped, and onDone is not called.
  • A later value fails. For example, a promise resolves to a function. That result is not sent, and the rest of the value continues. onDone still runs. If the value came from an async iterable, the serializer also stops reading it and calls its return method, as the JSON stream mode does. The receiver rejects the payload when the input ends, because that promise never settled.
  • A cleanup throws after every value settled. onError receives the first error, and onDone is not called.

Deserializing

binary.deserialize(options) takes:

OptionTypeDefaultDescription
read()functionrequiredReturns a promise for the next chunk, or for undefined at the end of the input.
onError(error)functionrequiredRuns when the input is invalid or a value cannot be rebuilt. It receives the error itself, such as the error a plugin's deserialize threw, not a SerovalDeserializationError.
refsReferenceMapa new mapThe map from binary.createReferenceMap(). Share one to resolve references between payloads.
pluginsPlugin[]nonePlugins for extra types. They need the same tags as the sender's.
disabledFeaturesnumber0Feature flags to reject.
featuresnumberall featuresThe features to accept, as a bit mask. Overrides disabledFeatures.
maxArrayBufferLengthnumber1000000The largest ArrayBuffer, in bytes, that the input may hold.
maxArrayLengthnumber1000000The largest array length that the input may hold, and the most holes that all its arrays may hold together.
signalAbortSignalnoneStops decoding when it aborts. See Stopping decoding.

It returns a promise for { value, pending }. The value is wrapped, so a root value that is a promise is handed over as is. pending is the number of promises and streams in the value that have not settled or ended yet. The promise resolves as soon as the root value is decoded, with every object, array, Map and Set in it filled in. Promises and streams inside the value may still be pending.

read can return chunks of any size. A node may be split across chunks, and one chunk may hold many nodes.

Stopping decoding

Pass an AbortSignal as signal to stop decoding, for example when the connection closes:

JavaScript
const controller = new AbortController();
socket.addEventListener('close', () => controller.abort(new Error('closed')));

const { value } = await binary.deserialize({ read, onError() {}, signal: controller.signal });

When the signal aborts, decoding stops calling read. The returned promise, if it has not resolved yet, every promise that has not settled and every stream that has not ended are rejected with the abort reason.

Untrusted input

binary.deserialize treats its input as untrusted:

  • It never evaluates code from the input.
  • It checks every node against the rules in the binary format. For example, a reference must point to a value that was already declared, with a type the node accepts.
  • It defines reserved property names such as __proto__ and constructor as own properties instead of assigning them.
  • It rejects typed arrays longer than 1,000,000 elements, DataViews longer than 1,000,000 bytes and RegExp patterns longer than 20,000 characters. It accepts at most 32 Unicode property escapes such as \p{L} across the RegExp values of one payload, like the JSON functions.
  • It rejects an ArrayBuffer longer than maxArrayBufferLength bytes, 1,000,000 by default, as soon as it reads the length, with SRV027. Raise the limit to receive larger files.
  • It rejects an array longer than maxArrayLength, 1,000,000 by default. An array states its length up front and its holes take no bytes, so without the limit a few bytes could claim an array of billions of holes. The holes of all the arrays in one payload also count against this limit. Both throw SRV028. Raise the limit to receive larger or sparser arrays.
  • It rejects RegExp and Temporal values when their feature is disabled.

When the input is invalid, or when it ends before every value has settled:

  • the error goes to onError;
  • the returned promise is rejected, if it has not resolved yet;
  • promises that have not settled are rejected with the error;
  • streams that have not ended are thrown into with the error.

If read() rejects, for example because the connection dropped, the same happens with that error.

Some errors only go to onError, and decoding continues. This happens when one property, entry or element cannot be set, for example because a plugin fails to rebuild it. The rest of the value is still decoded without it. Treat any call to onError as a failed payload.

Note

binary.deserialize limits no total size. The decoder keeps every chunk it reads until the node is complete. Limit the size of the input in your transport.

Sharing references between payloads

Pass the same reference maps to several payloads, and a later payload can refer to values an earlier one sent, instead of sending them again. The serializer uses a Map, and the deserializer uses binary.createReferenceMap().

JavaScript
import * as binary from 'seroval/binary';

// One map on each side, shared by every payload.
const serializerRefs = new Map();
const deserializerRefs = binary.createReferenceMap();

function send(value) {
  const chunks = [];
  return new Promise((resolve, reject) => {
    binary.serialize(value, {
      refs: serializerRefs,
      onSerialize(bytes) {
        chunks.push(bytes);
      },
      onDone() {
        resolve(chunks);
      },
      onError: reject,
    });
  });
}

async function receive(chunks) {
  let index = 0;
  const { value } = await binary.deserialize({
    refs: deserializerRefs,
    async read() {
      return chunks[index++];
    },
    onError(error) {
      console.error(error);
    },
  });
  return value;
}

const user = { name: 'Ada' };

const first = await receive(await send({ user }));
const second = await receive(await send({ author: user }));

second.author === first.user; // true

Decode the payloads in the order they were sent, with the same pair of maps. If a payload refers to a value the receiver never decoded, onError receives an error such as SerovalMissingBinaryRefError, and the value is incomplete. In a session, push throws that error instead.

Payloads that stream at once

binary.deserialize decodes asynchronously, so two payloads that stream at the same time can decode out of order. binary.createDeserializer() creates a session for that case, as createCrossDeserializer does for JSON. Each payload of the session takes its bytes through push, which decodes them before it returns, so the payloads decode in the order their bytes arrive. Serialize them with one refs map, and push the bytes in the order the serializers produced them.

JavaScript
const session = binary.createDeserializer();
const payload = session.open();

// For each chunk of the payload, as it arrives:
payload.push(chunk);
// Once the payload's bytes end:
payload.end();

const { value } = await payload.result;

createDeserializer takes the options of binary.deserialize except read, refs and signal, and its onError is optional. A payload has:

MemberDescription
push(chunk)Decodes every node that the chunk completes. Throws when the bytes are malformed, and aborts the payload with the error. Does nothing once the payload is aborted.
end()Ends the payload. Throws when it is incomplete, and aborts the payload with the error.
abort(reason)Rejects the root value if it is not decoded yet, and every promise and stream of the payload that is still open.
resultA promise for { value, pending }, as binary.deserialize returns.
pendingThe promises and streams of the payload that have not settled or ended yet.

The session has open(options?), pending across the payloads that have not ended, and abort(reason), which aborts every payload that has not ended and makes later calls to open throw a SerovalAbortedError. The session forgets a payload once it ends or aborts. An error that stops a payload after push or end returned, such as a plugin whose deserialize fails, aborts the payload and goes to onError. Pass { onError } to open to receive the errors of one payload instead.

When a value fails, the serializer sends the nodes it wrote before it calls onError. A later payload can then refer to them, even though the value that sent them failed.

Live streams

A live stream is sent one event at a time. If onSerialize returns a promise, the event behind that chunk is accepted only after the promise resolves, so the producer waits for the transport. An async iterable, and a stream that a plugin made with ctx.streamSource, are read the same way: the next value is pulled only after the chunk of the previous one is accepted. Other chunks, such as settled promises and events of a createStream stream, are not held back.

JavaScript
import { createLiveStream } from 'seroval';
import * as binary from 'seroval/binary';

const { stream, producer } = createLiveStream();

binary.serialize(
  { events: stream },
  {
    refs: new Map(),
    onSerialize(bytes) {
      // A WritableStream writer returns a promise, which applies backpressure.
      return writer.write(bytes);
    },
    onDone() {
      writer.close();
    },
    onError(error) {
      writer.abort(error);
    },
  },
);

for await (const event of source) {
  // Resolves once the chunk for this event was written.
  await producer.write(event);
}

Stopping the serializer cancels the live stream, and its onCancel runs.

On the receiving side, a live stream keeps its values only until the first listener subscribes. After that, it passes values on without storing them, and a second listener throws.

Isomorphic references

Values registered with createReference are sent by their key, as in the other modes. The receiver must register a value under the same key, or decoding fails with SerovalMissingReferenceForIdError.

An OpaqueReference sends its replacement, as in the other modes.

Plugins

A plugin works in binary mode through its binary section. See Writing plugins. Every plugin in seroval-plugins has one.

Pass the same plugins on both sides. A value that matches a plugin with no binary section makes serialization fail with a TypeError.

Wire format

The binary format page describes every node, its byte layout and the rules the decoder checks.

The format can change in a minor release. Both sides must use the same seroval version. See Compatibility.