pure-cbor
CBOR for JavaScript and TypeScript, with two promises:
- Clean, functional code. Pure functions over explicit state, in the spirit of OCaml: no classes (apart from the error type), no state kept between calls apart from a documented cache of decoded map keys, immutable tagged variants, and one named set of wire constants. About 2,800 lines of strict TypeScript, with no runtime dependencies, no Node APIs and no generated code (CSP-safe).
- The fastest standard CBOR library for JavaScript. Pure JS, no native addon. On public benchmark data it decodes 1.16–1.71× faster than cbor-x, the next fastest of the six other CBOR libraries measured, and encodes level with it to 1.50× faster (cbor-x also measured as pure JS, without its optional native addon). Small messages decoded from a fresh buffer are 5–12× faster. It isn't ahead everywhere: some small mixed arrays and objects are level, and on COSE and WebAuthn messages it matches cbor-x only with
binaryOwnership: 'borrow', since cbor-x returns views into the input by default while pure-cbor copies. Details in BENCHMARK.md.
It covers the whole RFC 8949 data model (tags, bignums, dates, Map, simple values, typed arrays), deterministic encoding, CBOR sequences over Web Streams, and COSE, CWT, WebAuthn and mdoc messages, checked against their published test vectors. Standard CBOR only: no private wire format.
Install
npm install pure-cbor
Plain ESM with TypeScript declarations, needing only ES2023 and TextEncoder/TextDecoder. Tested on Node 22, 24 and 26 and on Deno; it should also run in Bun, browsers and workers, but those aren't tested yet.
import { encode, decode } from 'pure-cbor';
const bytes = encode({ id: 7, name: 'Ada', tags: ['x', 'y'], active: true, manager: null });
console.log(decode(bytes)); // { id: 7, name: 'Ada', tags: ['x', 'y'], active: true, manager: null }
console.log(decode(encode(new Float64Array([1.25, -0, Math.PI])))); // Float64Array
Functional core
import { binary, read, readWhole, write, maxEncodedSize } from 'pure-cbor';
import type { Value } from 'pure-cbor';
const values: Value[] = [42, 'hello', { list: [1, 'x'] }, new Float32Array([1, 2, 3])];
const capacity = values.reduce((total, value) => total + maxEncodedSize(value), 0);
const buffer = binary(new Uint8Array(capacity));
let offset = 0;
for (const value of values) offset = write(buffer, offset, value);
// A CBOR sequence (not a CBOR array).
const used = binary(buffer.bytes.subarray(0, offset));
for (let position = 0; position < offset;) {
const [value, next] = read(used, position);
console.log(value);
position = next;
}
// If the prepared view contains exactly one value, no sequence tuple is needed.
console.log(readWhole(binary(new Uint8Array([0x83, 1, 2, 3])))); // [1, 2, 3]
Binary holds a byte view. It has no cursor and deliberately no DataView: in V8, constructing a DataView on a small, freshly allocated buffer forces the buffer off-heap. That cost ~900 ns per message, more than the encode or decode itself. Writes mutate only the supplied bytes and return the next offset. Reads do not change the source. Offsets are relative to the supplied view, including subviews with a nonzero byteOffset.
The codecs have no hidden operation state. The shared module resources are:
- constants and a tag lookup;
- standard UTF-8 encoders/decoders, used with non-streaming calls;
- two scratch areas used only within one synchronous call: a one-element float array for float/byte conversion, and the owned-output staging buffer;
- a decoded-key cache (see below).
Decoding a container creates one small state record (cursor, depth, limits) for that call and passes it down explicitly.
Allocation policies
Choose the API based on the lifetime of your data, not merely its speed.
1. Owned output (default)
const owned = encode({ hello: 'world' });
Exactly sized, with no shared backing buffer. The bytes can be retained or transferred to another worker.
2. Caller-owned buffer
import { binary, write, encodeInto } from 'pure-cbor';
const destination = new Uint8Array(1024);
const prepared = binary(destination);
let offset = write(prepared, 0, 42);
offset = write(prepared, offset, 'hello');
// Or encodeInto(value, destination, offset).
The fastest interface for scalars when you manage memory yourself. A capacity error never partially writes the destination. For arrays and objects this guarantee costs a sizing pass before writing, so owned encode() can be faster for objects.
3. Slab-backed encoder (opt-in)
import { createSlabEncoder, decode } from 'pure-cbor';
const pooled = createSlabEncoder({ slabSize: 64 * 1024, maxPooledValueSize: 16 * 1024 });
const first = pooled(42);
const second = pooled({ list: [1, 'hello'] });
console.log(first.buffer === second.buffer); // true for these two small values
console.log(decode(first)); // 42, even after later calls
- When it helps: outputs of 64 bytes or less are already cheap V8 on-heap allocations with
encode(), so a slab mainly saves the ~0.5 µs off-heap allocation for larger messages.
- Allocates its slab lazily. Only one active slab is retained by the closure.
- Appends each value into disjoint memory. On rollover it allocates a new slab, and earlier returned views are never overwritten.
- Values whose encoded size exceeds
maxPooledValueSize get exact owned output instead, so an unusually large value never grows the pool. The default threshold is one quarter of the slab size; zero disables pooling.
- Each returned view may keep its whole backing slab alive.
- Treat the returned view as the message, not
view.buffer. Other messages may share the backing buffer, so don't transfer or detach it, share it with untrusted code, or write outside your slice. Use encode() or Uint8Array.from(view) for independent ownership.
createSlabEncoder returns a function, not a serializer class. Separate instances share nothing. Reentrant calls fall back to owned allocation.
Streaming
A CBOR sequence (RFC 8742, media type application/cbor-seq) is complete CBOR items written back to back. These functions read and write sequences over Web Streams, which are built into browsers, Node ≥ 18, Deno, Bun and workerd, and over any async iterable of bytes, including Node streams.
import { decodeStream, decodeSequence, encodeSequence, encodeStream } from 'pure-cbor';
// Decode a response body item by item.
for await (const value of decodeSequence(response.body!)) handle(value);
// Or as a TransformStream: bytes in, values out.
const values = response.body!.pipeThrough(decodeStream({ maxItemBytes: 1 << 20 }));
// Batch mode: one array of values per chunk, far less Web Streams overhead.
for await (const batch of response.body!.pipeThrough(decodeStream({ batch: true }))) batch.forEach(handle);
batches.pipeThrough(encodeStream({ batch: true })).pipeTo(destination); // arrays of values in
// Stream values out as a request body. chunkBytes coalesces values into larger chunks.
await fetch(url, {
method: 'POST', duplex: 'half', headers: { 'content-type': 'application/cbor-seq' },
body: encodeSequence(rows, { chunkBytes: 16384 }),
});
source.pipeThrough(encodeStream()).pipeTo(destination);
Without streams, for example with WebSocket messages, Node 'data' events or tests, use the incremental core directly:
import { createSequenceDecoder, createSequenceEncoder } from 'pure-cbor';
const decoder = createSequenceDecoder();
socket.onmessage = event => decoder.push(new Uint8Array(event.data), handle);
socket.onclose = () => decoder.end(); // throws `truncated` if an item was cut off
const encoder = createSequenceEncoder({ chunkBytes: 16384 });
for (const row of rows) encoder.push(row, send);
encoder.flush(send);
Decoding
- Items that sit inside a chunk are decoded in place, with nothing extra.
- An item that runs past the end of a chunk is gathered by a header-only scanner. The scanner allocates nothing and resumes where it stopped, so decoding is linear in the input whatever the chunking.
- Near the end of each chunk, items are checked with the scanner before decoding, so a cut-off item is detected without an exception.
- Malformed input reports the same error code however it's chunked.
- Errors carry absolute stream offsets.
Limits
maxItemBytes (default 16 MiB) caps one item's encoded size. It's checked from headers before the bytes arrive, so a short header claiming a 4 GB string can't make the decoder buffer it.
- All decode limits (
maxDepth, maxArrayLength, maxMapEntries, the allocation budget) apply to each item.
Encoding
chunkBytes: 0 (the default) emits one owned chunk per value: lowest latency, right for interactive transports.
chunkBytes: N writes values straight into chunks and emits each once it holds at least N bytes, so chunks hold N to N + one value bytes. This is right for files and HTTP bodies.
- An unsupported value throws and leaves no partial bytes behind.
Notes
decodeSequence cancels the source if you stop iterating early.
encodeSequence pulls values lazily as the stream is read.
- A decoder that has thrown stays failed.
push after end(), or from inside its own callback, throws a TypeError.
- With
binaryOwnership: 'borrow', values may alias incoming chunks. That's safe with ordinary readers, but not with producers that reuse chunk buffers, such as BYOB readers.
- Batch mode (
batch: true) moves values as arrays. Each Web Streams step costs about 1 µs in Node, more than decoding a small value, so for many small values prefer batch mode, decodeSequence or the core. Batched decodeStream is within 8% of the core decoder, and batched encodeStream is 3.4× faster than cbor-x's Node EncoderStream (see BENCHMARK.md).
decodeStream({ batch: true }) emits one array per input chunk that completes at least one value.
encodeStream({ batch: true }) accepts arrays. With chunkBytes: 0 it emits one chunk per array; with chunkBytes: N it coalesces as usual.
- Build sources that pull lazily. Enqueuing many items into a
ReadableStream up front made Node's stream queue quadratic: 100,000 items took 2.7 s to read back.
COSE, CWT, WebAuthn and mdoc
These formats are tested against their own specifications' examples (see test/vectors): every COSE working-group example, the RFC 8392 CWTs, all WebAuthn Level 3 attestations, and the ISO 18013-5 mobile driving licence flow.
import { binary, decode, encode, read, isTagged, tagged } from 'pure-cbor';
// COSE_Sign1: rebuild the exact bytes the signature covers.
const message = decode(bytes, { binaryOwnership: 'borrow' }); // views: much faster for byte-heavy messages
const [protectedHeader, unprotectedHeader, payload, signature] = isTagged(message) ? message.value : message;
const algorithm = decode(protectedHeader).get(1); // integer keys decode as Map
const toBeSigned = encode(['Signature1', protectedHeader, externalAad, payload]);
// WebAuthn authenticatorData: the COSE public key has no length prefix, so
// read() decodes one item and returns where it ended (extensions may follow).
const [publicKey, next] = read(binary(authData), 55 + credentialIdLength);
// Keep tags exactly as written (e.g. to re-encode signed data byte for byte):
decode(bytes, { tags: { 0: content => tagged(0, content) } });
Byte strings are copied by default, so results never depend on the input buffer. Byte strings over 64 bytes from one decode share one arena, so a COSE or WebAuthn message costs about one allocation, not one per key, signature or certificate. Decoding with binaryOwnership: 'borrow' returns views into the input instead. That's faster still (no copy at all), and safe while the input stays unchanged. Tag 24 (embedded CBOR, used by mdoc) decodes as Tagged(24, bytes); decode its value to get the inner item.
API
| Function |
Contract |
encode(value) |
Exact-sized, independently owned Uint8Array. |
createSlabEncoder(options?) |
A bounded, append-only slab encoder closure. |
decode(bytes, options?) |
Decode exactly one item; reject trailing bytes. |
encodeInto(value, bytes, offset = 0) |
Write into caller-owned memory, return the next offset. |
binary(bytes) |
Validate and wrap a byte view for reuse. |
write(binary, offset, value) |
Prepared-buffer write, with bounds checks. |
read(binary, offset, options?) |
Read one item; return [value, nextOffset]. May leave trailing bytes. |
readWhole(binary, options?) |
Read exactly one item from a prepared view; no result tuple. |
encodedSize(value) |
Exact encoded size. Strings may need a UTF-8 sizing pass. |
maxEncodedSize(value) |
Upper bound. Exact for numbers, typed arrays and numeric-only arrays. |
tryDecode(bytes, options?) |
Discriminated Result; catches library validation errors, not arbitrary programmer/runtime errors. |
createSequenceDecoder(options?) |
Incremental CBOR-sequence decoder: push(chunk, onValue), end(). |
createSequenceEncoder(options?) |
Sequence encoder: push(value, onChunk), flush(onChunk). |
decodeStream(options?) |
TransformStream from bytes to values, or to arrays of values with batch: true. |
encodeStream(options?) |
TransformStream from values, or arrays of values with batch: true, to bytes. |
decodeSequence(source, options?) |
Async generator of values from a ReadableStream or (async) iterable of byte chunks. |
encodeSequence(values, options?) |
ReadableStream of bytes from an iterable or async iterable of values. |
Inputs must be stable during a call: no accessors that change values, proxies, or concurrent mutation (the sizing and writing passes assume stable values). Don't forge Binary descriptors, or resize or detach buffers during an operation. Allocation can fail with a native runtime error for excessively large values.
Wire types
type Scalar = number | bigint | string | boolean | null | undefined;
type Value = Scalar | TypedArray | Date | Tagged | SimpleValue
| readonly Value[] | ReadonlyMap<Value, Value> | ValueObject;
interface ValueObject { readonly [key: string]: Value }
interface Tagged { readonly tag: number; readonly value: Value } // tagged(tag, value)
interface SimpleValue { readonly simple: number } // simple(n)
Tagged and SimpleValue are immutable variants made by tagged() and simple(). They're recognized by a private prototype, so a plain object with the same fields is just an object.