# Protobuf, MessagePack and CBOR

URL: https://docs.folkways.io/docs/realtime-api/payloads/other-formats

Publish and receive Protocol Buffers, MessagePack and CBOR payloads, and what to check on the way in.

Folkways carries Protobuf, MessagePack and CBOR bytes without reading them. Encode before publishing, set the content
type, and decode on the way in after checking it.

## Protocol Buffers [#protocol-buffers]

```proto title="telemetry.proto"
syntax = "proto3";
package fleet;

message Reading {
  string device_id = 1;
  double temperature = 2;
  uint64 timestamp_ms = 3;
}
```

With [protobufjs](https://www.npmjs.com/package/protobufjs) in Node.js:

```ts
import protobuf from 'protobufjs';

const root = await protobuf.load('telemetry.proto');
const Reading = root.lookupType('fleet.Reading');

const reading = { deviceId: 'sensor-42', temperature: 21.5, timestampMs: Date.now() };
const problem = Reading.verify(reading);
if (problem) throw new Error(problem);

await sensors.publish('reading', Reading.encode(Reading.create(reading)).finish(), { contentType: 'protobuf' });
```

Receivers check `contentType === 5`, then `Reading.decode(message.payload)`. A `uint64` may come back as a `Long`,
a `bigint` or a string depending on the library. Reserve the numbers and names of removed fields; never reuse them.

## MessagePack and CBOR [#messagepack-and-cbor]

Use a codec such as [@msgpack/msgpack](https://www.npmjs.com/package/@msgpack/msgpack) or
[cbor-x](https://www.npmjs.com/package/cbor-x):

```ts
import { encode, decode } from '@msgpack/msgpack';

await room.publish('move', encode({ x: 10, y: 20 }), { contentType: 'msgpack' });

room.subscribe((message) => {
  if (message.contentType !== 6) return; // MsgPack
  const move = decode(message.payload);
});
```

CBOR is `contentType: 'cbor'` (7). Neither format enforces your data model: validate what you decode.

## Rules for any format [#rules-for-any-format]

- Decide by the declared content type and your schema version, never by sniffing the first bytes.
- Refuse formats you don't support, safely.
- Validate after decoding; see [Schemas](/docs/realtime-api/payloads/schemas).
