Payload Formats
Encode text or JSON, validate received data, and adapt a serializer with no change to the SDK.
Before you start: obtain a connected chat segment with the setup from Messaging. Each format below is an alternative. Both the sender and the receiver must agree on the format.
1. Start with text
Use these alternatives in the <script setup> of the Quickstart's frontend/src/ChatRoom.vue. Replace the chat.onMessage() listener and the payload in send().
import { textPayload, readText } from "@useceleris/client";
const stopText = chat.onMessage((payload) => console.log(readText(payload)));
await chat.publish({ payload: textPayload("Hello") });
// Later, when this receiver is no longer needed:
stopText();
Celeris carries opaque bytes. It does not infer a content type, compress JSON automatically, or translate formats for recipients.
2. Send and validate JSON
Install a validator explicitly in your application:
npm install zod
import { jsonPayload, readJson } from "@useceleris/client";
import { z } from "zod";
const typingSchema = z.object({
type: z.literal("typing"),
active: z.boolean(),
});
const stopJson = chat.onMessage((payload) => {
try {
const result = typingSchema.safeParse(readJson(payload));
if (!result.success) {
console.warn("Ignored an invalid typing event.");
return;
}
console.log("Peer typing:", result.data.active);
} catch {
console.warn("Ignored a payload that was not valid JSON.");
}
});
await chat.publish({
payload: jsonPayload({ type: "typing", active: true }),
});
// Later:
stopJson();
In TypeScript, readJson<MyType>() asserts a type. It does not validate received data. Validate anything received from a publisher that you do not control. Render received text safely. Do not insert it as HTML.
jsonPayload() uses JavaScript's JSON.stringify(). It throws ConfigurationError if serialization throws, such as for a circular object or a bigint, or produces no JSON at all. It is not schema validation. Values such as NaN become null, and it omits object properties that contain undefined. Validate application data before you encode it. The read helpers reject invalid UTF-8 or malformed JSON.
3. Bring your own serializer
The SDK includes one adapter, not a separate bundled library for every format. createPayloadCodec({ encode, decode }) takes two functions:
encode(value)turns a value into aUint8Array.decode(bytes)turns received bytes back into a value.
The adapter makes sure that both are functions. Otherwise, it throws ConfigurationError. It returns an object with encodePayload(value) and readPayload(payload), which call your functions directly. The adapter does not validate values. Errors from your encoder or decoder propagate unchanged. If your encoder returns something that is not a Uint8Array, publish() rejects it with ConfigurationError. The sender and the receiver must use compatible codecs.
MessagePack
Install your chosen serializer:
npm install @msgpack/msgpack
import { createPayloadCodec } from "@useceleris/client";
import { encode, decode } from "@msgpack/msgpack";
const codec = createPayloadCodec({ encode, decode });
const stopBinary = chat.onMessage((payload) => {
const value = codec.readPayload(payload);
console.log(value); // Validate the decoded value before trusting it.
});
await chat.publish({
payload: codec.encodePayload({ sensor: "temperature", value: 21.5 }),
});
// Later:
stopBinary();
Protobuf
This example uses the Quickstart's frontend and protobuf.js. It reads a small schema directly, so you do not need a code-generation step.
- Install the serializer in the Quickstart's
frontendfolder:
npm install protobufjs
- Create
frontend/src/reading.proto. Both tabs must use this schema:
syntax = "proto3";
package demo;
message Reading {
string sensor = 1;
double value = 2;
}
The numbers identify fields on the wire. Keep them stable when you change your schema.
- Create
frontend/src/reading-codec.ts:
import protobuf from "protobufjs";
import { createPayloadCodec } from "@useceleris/client";
import schemaSource from "./reading.proto?raw";
type Reading = { sensor: string; value: number };
const root = protobuf.parse(schemaSource).root;
const ReadingMessage = root.lookupType("demo.Reading");
function validateReading(reading: Reading) {
const error = ReadingMessage.verify(reading);
if (error) throw new Error("Invalid reading: " + error);
if (!reading.sensor.trim() || !Number.isFinite(reading.value)) {
throw new Error("A reading needs a sensor name and a finite value.");
}
}
export const protoCodec = createPayloadCodec<Reading>({
encode(reading) {
validateReading(reading);
return ReadingMessage.encode(reading).finish();
},
decode(bytes) {
const reading = ReadingMessage.decode(bytes) as unknown as Reading;
validateReading(reading);
return reading;
},
});
Vite's ?raw import loads the schema as a string. encode() returns a writer, and finish() produces the bytes that Celeris expects. verify() checks field types. validateReading() also checks this application's rules.
- In
frontend/src/ChatRoom.vue, add the import and replace thechat.onMessage()listener with this listener:
import { protoCodec } from "./reading-codec";
chat.onMessage((payload, meta) => {
try {
const reading = protoCodec.readPayload(payload);
const text = reading.sensor + ": " + reading.value;
show({ from: meta.tokenReference, text, at: Number(meta.timestamp) });
} catch {
console.warn("Ignored an invalid Protobuf reading.");
}
});
Keep chat.subscribe(). Do not register the old text or MessagePack listener as well.
- In
frontend/src/ChatRoom.vue, change the input placeholder fromWrite a messagetoSensor. Then replacesend():
async function send() {
const sensor = draft.value.trim();
if (!sensor) return;
draft.value = "";
await chat.publish({ payload: protoCodec.encodePayload({ sensor, value: 21.5 }) });
show({ from: props.me.id, text: sensor + ": 21.5", at: Date.now() });
}
Reload both tabs, join again, and wait until both show connected. Enter temperature in the Sensor field and press Send. The other tab then shows temperature: 21.5. The sender sees its local copy, not a received copy, unless your server enables echo. Publish completion still means local acceptance, not confirmed delivery.
A custom format
You can also write the encoder and the decoder yourself. The codec only needs the types to match:
encodetakes your value and returns aUint8Array.decodetakes the receivedUint8Arrayand returns your value.
import { createPayloadCodec } from "@useceleris/client";
export const positionCodec = createPayloadCodec({
// Takes your value. Must return a Uint8Array.
encode(position) {
// Your own logic: write the position into bytes.
return bytes;
},
// Takes the received Uint8Array. Returns your value.
decode(bytes) {
// Your own logic: read the position from the bytes.
return position;
},
});
Both ends must agree on your format. If the format can change, include a version number so that a receiver can tell the formats apart.
Mix text, JSON, MessagePack, and Protobuf receivers on one segment only when your application can distinguish the formats. Separate segments or an explicit envelope can provide that distinction. A successful Protobuf decode does not prove who sent the message or which schema they used. Keep authorization and application validation in place.
4. Handle timestamps
The SDK's metadata and your message payload are separate. Your serializer decides the types inside a payload. The SDK uses these types for its own numeric fields:
| Value | JavaScript type |
|---|---|
Presence request page and perPage | number |
Presence result total, perPage, currentPage, from, and to | number |
| Connection and presence-query timeouts in milliseconds | number |
Credential request disconnectedAt and replayLookbackMs | number when present |
Recovery event retryIndex | number |
Message, notice, presence-event, and presence-record timestamp | bigint |
Use normal number arithmetic for counts and pages, such as page + 1. Keep timestamps as bigint when their exact value matters. Do not convert them blindly with Number(). A 64-bit integer can exceed JavaScript's safe-integer range. Arithmetic cannot mix a bigint and a number.
In frontend/src/ChatRoom.vue, this listener prepares message metadata for a JSON API. It converts only the timestamp and leaves the SDK value unchanged:
const stopMetadata = chat.onMessage((_payload, metadata) => {
const serialized = JSON.stringify({
...metadata,
timestamp: metadata.timestamp.toString(),
});
console.log(serialized);
});
// Later:
stopMetadata();
The JSON timestamp is a decimal string, not a JSON number. A consumer that follows the same contract can use BigInt(record.timestamp) to restore it. Validate received records before conversion.
For nested SDK data, such as a presence page, use a replacer. Numeric counts remain JSON numbers, and nested timestamps become strings:
function stringifySdkData(value) {
return JSON.stringify(value, (_key, field) =>
typeof field === "bigint" ? field.toString() : field
);
}
// After connecting:
const result = await chat.presenceList({ page: 1, perPage: 25 });
const serialized = stringifySdkData(result);
ServerError.resource can also contain numbers, bigints, or nested arrays. The same replacer handles either numeric type. This is an application serialization convention, not a change to the SDK's runtime types. Do not log sensitive payloads, identities, or error resources in production.
After these steps, text arrives as a string, and valid JSON passes the schema. The listener ignores invalid JSON. The custom codec returns the object that you encoded.
Next: Presence. For format tradeoffs, see Binary Messaging.