Skip to content

Getting Started

Terminal window
bun add @zocket/core @zocket/server @zocket/client zod

For React integration, also add @zocket/react:

Terminal window
bun add @zocket/react

Actors are stateful units with typed methods, events, and lifecycle hooks.

chat.ts
import { z } from "zod";
import { actor, createApp } from "@zocket/core";
const ChatRoom = actor({
state: z.object({
messages: z.array(z.object({
from: z.string(),
text: z.string(),
})).default([]),
}),
methods: {
sendMessage: {
input: z.object({ from: z.string(), text: z.string() }),
handler: ({ state, input }) => {
state.messages.push(input);
},
},
},
});
export const app = createApp({ actors: { chat: ChatRoom } });
server.ts
import { serve } from "@zocket/server/bun";
import { app } from "./chat";
const server = serve(app, { port: 3000 });
console.log(`Zocket on ws://localhost:${server.port}`);
client.ts
import { createClient } from "@zocket/client";
import type { app } from "./chat";
const client = createClient<typeof app>({ url: "ws://localhost:3000" });
// Get a typed handle for a specific actor instance
const room = client.chat("general");
// Call methods — fully typed
await room.sendMessage({ from: "Alice", text: "Hello!" });
// Subscribe to state changes
room.state.subscribe((state) => {
console.log("Messages:", state.messages);
});
// Clean up when done
room.$dispose();
zocket.ts
import { createClient } from "@zocket/client";
import { createZocketReact } from "@zocket/react";
import type { app } from "./chat";
export const client = createClient<typeof app>({ url: "ws://localhost:3000" });
export const { ZocketProvider, useActor, useActorState } = createZocketReact<typeof app>();
App.tsx
import { ZocketProvider, useActor, useActorState, client } from "./zocket";
function Chat() {
const room = useActor("chat", "general");
const messages = useActorState(room, (s) => s.messages);
return (
<ul>
{messages?.map((m, i) => (
<li key={i}>{m.from}: {m.text}</li>
))}
</ul>
);
}
export function App() {
return (
<ZocketProvider client={client}>
<Chat />
</ZocketProvider>
);
}
  • Actors — full API for state, methods, events, and lifecycle hooks
  • Middleware — auth, context enrichment, gating
  • React HooksuseActor, useActorState, useEvent
  • Multiplayer Draw — complete example walkthrough