WebSocket Typed Message Protocol

Layer a typed message protocol over WebSocket with Zod parsing per message type, versioned envelopes, and safe close-frame handling.

TypescriptData Fetching

Code

typescriptsnippet
45 lines
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: zod and ws — install them before running the snippet.
  • The guard !envelope.success short-circuits the flow with an early return when 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

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.