WebSocket Typed Message Protocol
Layer a typed message protocol over WebSocket with Zod parsing per message type, versioned envelopes, and safe close-frame handling.
Code
import { z } from 'zod';
import { WebSocket } from 'ws';
const Envelope = z.object({
v: z.literal(1),
type: z.string(),
payload: z.unknown(),
});
const Messages = {
'tick.update': z.object({ symbol: z.string(), price: z.number() }),
'alert.raise': z.object({ level: z.enum(['warn', 'critical']), text: z.string() }),
};
type MessageType = keyof typeof Messages;
function parseMessage(raw: string) {
const envelope = Envelope.safeParse(JSON.parse(raw));
if (!envelope.success) return { ok: false, reason: 'bad envelope' };
const schema = Messages[envelope.data.type as MessageType];
if (!schema) return { ok: false, reason: 'unknown type ' + envelope.data.type };
const payload = schema.safeParse(envelope.data.payload);
return payload.success
? { ok: true, type: envelope.data.type, payload: payload.data }
: { ok: false, reason: 'bad payload for ' + envelope.data.type };
}
const socket = new WebSocket('wss://stream.example.com/v1');
socket.on('message', (data) => {
const parsed = parseMessage(data.toString());
if (!parsed.ok) {
socket.close(1002, 'protocol violation');
return;
}
if (parsed.type === 'tick.update') {
console.log(parsed.payload.symbol, parsed.payload.price);
}
});
socket.on('close', (code, reason) => {
console.log('closed', code, reason.toString());
});How it works
WebSocket Typed Message Protocol keeps everything in the function parseMessage.
z, WebSocket are the only symbols borrowed from zod — the coupling is explicit and narrow.
The result comes back as an object carrying false.
What to watch for
- External dependency:
zodandws— install them before running the snippet. - The guard
!envelope.successshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The primary signature is function parseMessage(raw: string)
The demo output is labeled (closed), so each printed line maps back to the step that produced it.
The call returns false.
Statements that matter
if (!schema) return { ok: false, reason: 'unknown type ' + envelope.data.type };
if (!envelope.success) return { ok: false, reason: 'bad envelope' };
type MessageType = keyof typeof Messages;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does `parseMessage` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- Do I need to install anything before running this?
- Yes: `zod` and `ws` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.