WebSocket · In depth

defineSocketContract

One shared Standard Schema contract validates wire payloads and infers client/server types. Route URLs choose the service; individual handler factories dispatch by message type.

Explain it like I’m five

The simple mental model

A socket contract is a shared form for both sides of a conversation. It says which messages exist and what each message must contain, so the server checks a message before handing it to the matching handler.

When it fits

When should I use it?

Use it when a site, app, or game client should share payload types and runtime validation with a routed Redweb service.

A practical API pattern

Follow the example

Taken directly from the complete socket recipe, including its setup and tests.

Read this article as Markdown

ts
import { defineSocketContract } from 'redweb/contract';
import { z } from 'zod';

const position = { x: z.number().int().min(-100).max(100), y: z.number().int().min(-100).max(100) };

// Share this module with a browser or Node client. It imports no server application code.
export const match = defineSocketContract('1', {
    join: z.object({ name: z.string().trim().min(1).max(40) }).strict(),
    move: z.object(position).strict(),
    resume: z.object({ session: z.string().uuid() }).strict(),
    state: z.object({ session: z.string().uuid(), name: z.string(), ...position }).strict(),
});
  1. 1

    The shared module defines join, move, resume, and state payload schemas once.

  2. 2

    The match route registers separate handlers created by the contract instead of switching on a secondary action field.

  3. 3

    The client and server validate their outgoing messages and parse incoming envelopes against the same schema.

Surface area

Methods and members

defineSocketContract(version, schemas, options?)

Creates an immutable contract and negotiated protocol policy from Standard Schema validators. Redweb does not require a particular validator at runtime.

handler(type, callback)

Creates a BaseHandler subclass. Validation completes before the callback receives its typed payload.

client(socket)

Wraps an existing WebSocket with typed, validated send and parse methods. It does not open or reconnect the connection.

send(socket, type, payload, metadata?)

Validates server output before sending through the normal transport and protocol policy.