defineSocketContract

Documentation for Redweb 0.13.3. Install that exact version when following these examples.

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

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 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.

Follow the example

This source is part of the complete socket recipe. Follow its setup and tests.

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. The shared module defines join, move, resume, and state payload schemas once.
  2. The match route registers separate handlers created by the contract instead of switching on a secondary action field.
  3. The client and server validate their outgoing messages and parse incoming envelopes against the same schema.

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.

What should I watch for?

Schema validation is not authentication or game-rule validation. Keep bearer session IDs private, apply authorization in handlers, and persist important data outside the starter's bounded in-memory sessions. Async validation deadlines cannot preempt synchronous JavaScript.