Skip to content
Built with

Durable State and WebSockets ​

SDK Reference

Imported from "void/durable". See Durable State for the file convention and where it is supported.

On this pageDefine durable state with defineDurableState · Add WebSockets to a durable module · Check method signatures

defineDurableState(definition) ​

Defines a typed, persisted Durable Object state machine. The returned object must be the default export of a module in durable-objects/. Also export it by name to make typed RPC calls from the rest of the app.

ts
function defineDurableState<TState, TEnv, TMethods>(definition: {
  name?: string;
  initialState: TState | ((env: TEnv) => TState | Promise<TState>);
  version?: number;
  migrations?: Array<{
    version: number;
    migrate(state: unknown): TState | Promise<TState>;
  }>;
  methods: TMethods;
  fetch?: (context, request: Request) => Response | Promise<Response>;
  alarm?: (context) => void | Promise<void>;
  storageKey?: string;
}): DurableStateApi<TMethods>;

DurableStateApi exposes class, get(name), get(namespace, name), getById(id), and getById(namespace, id). Stubs from the lookup helpers carry the definition's methods. Argument types are kept, and return values are wrapped in Promise.

name is optional. It fixes the persistent resource identity, so it no longer comes from the file name. Before you rename a deployed definition, run void info and pin the name it shows. Keep the instance names you pass to get() unchanged. See the migration flow.

WebSockets ​

Imported from "void/ws". defineRoom() adds shared-room helpers to hook contexts. defineWebSocket() gives a connection its socket helpers. Both need messages.client and messages.server Standard Schema validators. Both support the hooks in the WebSocket guide.

Both helpers accept these optional resource settings:

ts
name?: string;
key?: (context: { params: Record<string, string> }) => string;

name fixes the Worker class and binding identity. Without it, the identity comes from the route file. Before you move a deployed route, run void info and pin the name it shows.

key selects the route instance and its ctx.id. Without it, routes use parameter names and values in route order, such as room=general. Routes with no parameters use default. A callback must return a stable string synchronously. When you rename parameters, keep the full old key to keep the state. See moving routes and renaming parameters.

Next steps ​

implemented.stream AI