{"id":32689359,"url":"https://github.com/kriasoft/ws-kit","last_synced_at":"2026-04-10T15:45:15.895Z","repository":{"id":290290085,"uuid":"973922548","full_name":"kriasoft/ws-kit","owner":"kriasoft","description":"Type-safe WebSocket message routing \u0026 RPC for Bun, Cloudflare, and browser runtimes.","archived":false,"fork":false,"pushed_at":"2025-10-31T01:24:04.000Z","size":2325,"stargazers_count":25,"open_issues_count":1,"forks_count":1,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-10-31T01:24:05.827Z","etag":null,"topics":["bun","hono","honojs","http","pubsub","real-time","schema","server","socket","socket-io","web","websocket","websockets","ws","zod","zod-validation"],"latest_commit_sha":null,"homepage":"https://kriasoft.com/bun-ws-router/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kriasoft.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":["koistya"]}},"created_at":"2025-04-28T01:52:47.000Z","updated_at":"2025-10-31T00:31:54.000Z","dependencies_parsed_at":"2025-04-28T03:29:42.774Z","dependency_job_id":"399360a0-3764-4790-b931-e580a895e93b","html_url":"https://github.com/kriasoft/ws-kit","commit_stats":null,"previous_names":["kriasoft/bun-ws-router","kriasoft/ws-kit"],"tags_count":16,"template":false,"template_full_name":null,"purl":"pkg:github/kriasoft/ws-kit","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kriasoft%2Fws-kit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kriasoft%2Fws-kit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kriasoft%2Fws-kit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kriasoft%2Fws-kit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kriasoft","download_url":"https://codeload.github.com/kriasoft/ws-kit/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kriasoft%2Fws-kit/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":281975288,"owners_count":26592953,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-31T02:00:07.401Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bun","hono","honojs","http","pubsub","real-time","schema","server","socket","socket-io","web","websocket","websockets","ws","zod","zod-validation"],"created_at":"2025-11-01T13:00:55.491Z","updated_at":"2025-11-01T13:02:07.361Z","avatar_url":"https://github.com/kriasoft.png","language":"TypeScript","funding_links":["https://github.com/sponsors/koistya"],"categories":[],"sub_categories":[],"readme":"# WS-Kit — Type-Safe WebSocket Router\n\n[![npm version](https://img.shields.io/npm/v/@ws-kit/zod.svg)](https://www.npmjs.com/package/@ws-kit/zod)\n[![npm downloads](https://img.shields.io/npm/dm/@ws-kit/zod.svg)](https://www.npmjs.com/package/@ws-kit/zod)\n[![GitHub Actions](https://github.com/kriasoft/ws-kit/actions/workflows/main.yml/badge.svg)](https://github.com/kriasoft/ws-kit/actions)\n[![Chat on Discord](https://img.shields.io/discord/643523529131950086?label=Discord)](https://discord.gg/aW29wXyb7w)\n\nType-safe WebSocket router for Bun and Cloudflare with **Zod** or **Valibot** validation. Routes messages to handlers with full TypeScript support on both server and client.\n\n## ⚠️ Environment Requirements\n\n**WS-Kit is ESM-only** and optimized for modern runtimes:\n\n- **Bun** (recommended) — native ESM and WebSocket support\n- **Cloudflare Workers/Durable Objects** — native ESM support\n- **Node.js** (with bundler) — requires Node 18+ and a bundler like Vite, esbuild, or Rollup\n- **Browser** — works with modern bundlers\n\n**Not compatible** with CommonJS-only projects or legacy runtimes.\n\n## Monorepo Structure\n\nWS-Kit is organized as a modular monorepo with independent packages:\n\n- **`@ws-kit/core`** — Platform-agnostic router and type system (foundation)\n- **`@ws-kit/zod`** — Zod validator adapter with `createRouter()` helper\n- **`@ws-kit/valibot`** — Valibot validator adapter with `createRouter()` helper\n- **`@ws-kit/bun`** — Bun platform adapter with `serve()` high-level and `createBunHandler()` low-level\n- **`@ws-kit/cloudflare-do`** — Cloudflare Durable Objects adapter\n- **`@ws-kit/client`** — Universal browser/Node.js client\n- **`@ws-kit/redis-pubsub`** — Optional Redis PubSub for multi-server scaling\n\nCombine any validator adapter with platform-specific packages. Each platform package (e.g., `@ws-kit/bun`) exports both high-level convenience (`serve()`) and low-level APIs (`createBunHandler()`).\n\n### Key Features\n\n**Server (Bun)**\n\n- 🔒 Type-safe message routing with Zod/Valibot validation\n- 🚀 Built on Bun's native WebSocket implementation\n- 📡 PubSub with schema-validated broadcasts\n- 🧩 Composable routers and middleware support\n\n**Client (Browser)**\n\n- 🔄 Auto-reconnection with exponential backoff\n- 📦 Configurable offline message queueing\n- ⏱️ Request/response pattern with timeouts\n- 🔐 Built-in auth (query param or protocol header)\n\n**Shared**\n\n- ✨ Shared schemas between server and client\n- ⚡ Choose Zod (familiar) or Valibot (60-80% smaller)\n- 🔒 Full TypeScript inference on both sides\n\n## Installation\n\nChoose your validation library and platform:\n\n```bash\n# With Zod on Bun (recommended for most projects)\nbun add @ws-kit/zod @ws-kit/bun\nbun add zod bun @types/bun -D\n\n# With Valibot on Bun (lighter bundles)\nbun add @ws-kit/valibot @ws-kit/bun\nbun add valibot bun @types/bun -D\n```\n\n## Quick Start\n\nThe **export-with-helpers pattern** is the first-class way to use WS-Kit —no factories, no dual imports:\n\n```ts\nimport { z, message, createRouter } from \"@ws-kit/zod\";\nimport { serve } from \"@ws-kit/bun\";\n\n// Define message schemas with full type inference\nconst PingMessage = message(\"PING\", { text: z.string() });\nconst PongMessage = message(\"PONG\", { reply: z.string() });\n\n// Create type-safe router with optional connection data\ntype AppData = { userId?: string };\nconst router = createRouter\u003cAppData\u003e();\n\n// Register handlers — fully typed!\nrouter.on(PingMessage, (ctx) =\u003e {\n  console.log(`Received: ${ctx.payload.text}`); // ✅ Fully typed\n  ctx.send(PongMessage, { reply: `Got: ${ctx.payload.text}` });\n});\n\n// Serve with type-safe handlers\nserve(router, {\n  port: 3000,\n  authenticate(req) {\n    const token = req.headers.get(\"authorization\");\n    return token ? { userId: \"u_123\" } : undefined;\n  },\n});\n```\n\n**That's it!** Validator, router, messages, and platform adapter all come from focused packages. Type-safe from server to client.\n\n### Eliminating Verbose Generics with Declaration Merging\n\nFor applications with multiple routers, reduce repetition by declaring your connection data type once using TypeScript **declaration merging**. Then omit the generic everywhere — it's automatic:\n\n```ts\n// types/app-data.d.ts\ndeclare module \"@ws-kit/core\" {\n  interface AppDataDefault {\n    userId?: string;\n    email?: string;\n    roles?: string[];\n  }\n}\n```\n\nNow all routers automatically use this type — no repetition:\n\n```ts\n// ✅ No generic needed — automatically uses AppDataDefault\nconst router = createRouter();\n\nrouter.on(SecureMessage, (ctx) =\u003e {\n  // ✅ ctx.ws.data is properly typed with all default fields\n  const userId = ctx.ws.data?.userId; // string | undefined\n  const roles = ctx.ws.data?.roles; // string[] | undefined\n});\n```\n\nIf you need custom data for a specific router, use an explicit generic:\n\n```ts\ntype CustomData = { feature: string; version: number };\nconst featureRouter = createRouter\u003cCustomData\u003e();\n```\n\n### Do and Don't\n\n```\n✅ DO:  import { z, message, createRouter } from \"@ws-kit/zod\"\n❌ DON'T: import { z } from \"zod\"  (direct imports cause dual-package hazards)\n```\n\n## Validation Libraries\n\nChoose between Zod and Valibot — same API, different trade-offs:\n\n```ts\n// Zod - mature ecosystem, familiar method chaining API\nimport { z, message, createRouter } from \"@ws-kit/zod\";\nimport { serve } from \"@ws-kit/bun\";\n\n// Valibot - 60-80% smaller bundles, functional composition\nimport { v, message, createRouter } from \"@ws-kit/valibot\";\nimport { serve } from \"@ws-kit/bun\";\n```\n\n### Quick Comparison\n\n| Feature     | Zod                      | Valibot                  |\n| ----------- | ------------------------ | ------------------------ |\n| Bundle Size | ~5-6 kB (Zod v4)         | ~1-2 kB                  |\n| Performance | Baseline                 | ~2x faster               |\n| API Style   | Method chaining          | Functional               |\n| Best for    | Server-side, familiarity | Client-side, performance |\n\n## Serving Your Router\n\nEach platform adapter exports both high-level convenience and low-level APIs. All approaches support authentication, lifecycle hooks, and error handling.\n\n### Platform-Specific Adapters (Recommended)\n\nUse platform-specific imports for production deployments — they provide correct options, type safety, and clear errors:\n\n**High-level (recommended):**\n\n```ts\nimport { serve } from \"@ws-kit/bun\";\nimport { createRouter } from \"@ws-kit/zod\";\n\nconst router = createRouter();\nserve(router, { port: 3000 });\n```\n\n**Low-level (advanced control):**\n\n```ts\nimport { createBunHandler } from \"@ws-kit/bun\";\nimport { createRouter } from \"@ws-kit/zod\";\n\nconst router = createRouter();\nconst { fetch, websocket } = createBunHandler(router);\n\nBun.serve({\n  port: 3000,\n  fetch(req, server) {\n    if (new URL(req.url).pathname === \"/ws\") {\n      return fetch(req, server);\n    }\n    return new Response(\"Not Found\", { status: 404 });\n  },\n  websocket,\n});\n```\n\nBenefits:\n\n- **Zero runtime detection** — No overhead, optimal tree-shaking\n- **Type-safe options** — Platform-specific settings built-in (e.g., port for Bun)\n- **Clear error messages** — Misconfigurations fail fast with helpful guidance\n- **Deterministic behavior** — Same behavior across all environments\n\n**For Cloudflare Durable Objects:**\n\n```ts\nimport { createDurableObjectHandler } from \"@ws-kit/cloudflare-do\";\nimport { createRouter } from \"@ws-kit/zod\";\n\nconst router = createRouter();\nconst handler = createDurableObjectHandler(router, {\n  authenticate(req) {\n    /* ... */\n  },\n});\n\nexport default {\n  fetch(req: Request) {\n    return handler.fetch(req);\n  },\n};\n```\n\n### Authentication\n\nSecure your router by validating clients during the WebSocket upgrade. Pass authenticated user data via the `authenticate` hook — all handlers then have type-safe access to this data:\n\n```ts\nimport { z, message, createRouter } from \"@ws-kit/zod\";\nimport { serve } from \"@ws-kit/bun\";\nimport { verifyIdToken } from \"./auth\"; // Your authentication logic\n\n// Define secured message\nconst SendMessage = message(\"SEND_MESSAGE\", {\n  text: z.string(),\n});\n\n// Define router with user data type\ntype AppData = {\n  userId?: string;\n  email?: string;\n  roles?: string[];\n};\n\nconst router = createRouter\u003cAppData\u003e();\n\n// Global middleware for auth checks\nrouter.use((ctx, next) =\u003e {\n  if (!ctx.ws.data?.userId \u0026\u0026 ctx.type !== \"LOGIN\") {\n    ctx.error(\"UNAUTHENTICATED\", \"Not authenticated\");\n    return; // Skip handler\n  }\n  return next();\n});\n\n// Handlers have full type safety\nrouter.on(SendMessage, (ctx) =\u003e {\n  const userId = ctx.ws.data?.userId; // ✅ Type narrowed\n  const email = ctx.ws.data?.email; // ✅ Type narrowed\n  console.log(`${email} sent: ${ctx.payload.text}`);\n});\n\n// Authenticate and serve\nserve(router, {\n  port: 3000,\n  authenticate(req) {\n    // Verify JWT or session token\n    const token = req.headers.get(\"authorization\")?.replace(\"Bearer \", \"\");\n    if (token) {\n      const decoded = verifyIdToken(token);\n      return {\n        userId: decoded.uid,\n        email: decoded.email,\n        roles: decoded.roles || [],\n      };\n    }\n  },\n  onError(error, ctx) {\n    console.error(`ws-kit error in ${ctx?.type}:`, error);\n  },\n  onOpen(ctx) {\n    console.log(`User ${ctx.ws.data?.email} connected`);\n  },\n  onClose(ctx) {\n    console.log(`User ${ctx.ws.data?.email} disconnected`);\n  },\n});\n```\n\nThe `authenticate` function receives the HTTP upgrade request and returns user data that becomes `ctx.ws.data` in all handlers. If it returns `null` or `undefined`, the connection is rejected.\n\n## Message Schemas\n\nUse the `message()` helper directly — no factory pattern needed:\n\n```ts\nimport { z, message } from \"@ws-kit/zod\";\n\n// Define your message types\nexport const JoinRoom = message(\"JOIN_ROOM\", {\n  roomId: z.string(),\n});\n\nexport const UserJoined = message(\"USER_JOINED\", {\n  roomId: z.string(),\n  userId: z.string(),\n});\n\nexport const UserLeft = message(\"USER_LEFT\", {\n  userId: z.string(),\n});\n\nexport const SendMessage = message(\"SEND_MESSAGE\", {\n  roomId: z.string(),\n  text: z.string(),\n});\n\n// With Valibot\nimport { v, message } from \"@ws-kit/valibot\";\n\nexport const JoinRoom = message(\"JOIN_ROOM\", {\n  roomId: v.string(),\n});\n```\n\nSimple, no factories, one canonical import source.\n\n### Request-Response Pairs with `rpc()`\n\nFor request-response patterns, use `rpc()` to bind request and response schemas together — no schema repetition at call sites:\n\n```ts\nimport { z, rpc, createRouter } from \"@ws-kit/zod\";\n\n// Define RPC schema - binds request to response type\nconst Ping = rpc(\"PING\", { text: z.string() }, \"PONG\", { reply: z.string() });\nconst Query = rpc(\"QUERY\", { id: z.string() }, \"RESULT\", { data: z.string() });\n\n// With Valibot\nimport { v, rpc } from \"@ws-kit/valibot\";\nconst Ping = rpc(\"PING\", { text: v.string() }, \"PONG\", { reply: v.string() });\n```\n\nThe client auto-detects the response type from the RPC schema, eliminating the need to specify it separately on every request.\n\n### RPC Handlers\n\nRegister RPC handlers with `router.rpc()` to use request/response pattern with `ctx.reply()` and `ctx.progress()`:\n\n```ts\nimport { z, rpc, createRouter } from \"@ws-kit/zod\";\n\nconst GetUser = rpc(\"GET_USER\", { userId: z.string() }, \"USER_DATA\", {\n  name: z.string(),\n  email: z.string(),\n});\n\nconst router = createRouter();\n\nrouter.rpc(GetUser, (ctx) =\u003e {\n  const { userId } = ctx.payload;\n\n  // Send terminal response (one-shot)\n  ctx.reply({ name: \"Alice\", email: \"alice@example.com\" });\n});\n```\n\nFor streaming responses, use `ctx.progress()` for non-terminal updates before the final `ctx.reply()`:\n\n```ts\nconst DownloadFile = rpc(\n  \"DOWNLOAD_FILE\",\n  { fileId: z.string() },\n  \"FILE_CHUNK\",\n  { chunk: z.string(), finished: z.boolean() },\n);\n\nrouter.rpc(DownloadFile, (ctx) =\u003e {\n  const { fileId } = ctx.payload;\n\n  // Send progress updates (non-terminal)\n  ctx.progress({ chunk: \"data...\", finished: false });\n  ctx.progress({ chunk: \"more...\", finished: false });\n\n  // Send terminal response (final)\n  ctx.reply({ chunk: \"end\", finished: true });\n});\n```\n\n**Fire-and-forget vs RPC:**\n\n- `router.on(Message, handler)` — Use `ctx.send()` for fire-and-forget messages\n- `router.rpc(RpcSchema, handler)` — Use `ctx.reply()` (terminal) and `ctx.progress()` (streaming) for request/response\n\n## Handlers and Routing\n\nRegister handlers with full type safety. The context includes schema-typed payloads, connection data, and lifecycle hooks:\n\n```ts\nimport { z, message, createRouter } from \"@ws-kit/zod\";\nimport { JoinRoom, UserJoined, SendMessage, UserLeft } from \"./schema\";\n\ntype ConnectionData = {\n  userId?: string;\n  roomId?: string;\n};\n\nconst router = createRouter\u003cConnectionData\u003e();\n\n// Handle new connections\nrouter.onOpen((ctx) =\u003e {\n  console.log(`Client connected: ${ctx.ws.data.userId}`);\n});\n\n// Handle specific message types (fully typed!)\nrouter.on(JoinRoom, (ctx) =\u003e {\n  const { roomId } = ctx.payload; // ✅ Fully typed from schema\n  const userId = ctx.ws.data?.userId;\n\n  // Update connection data\n  ctx.assignData({ roomId });\n\n  // Subscribe to room broadcasts\n  ctx.subscribe(roomId);\n\n  console.log(`User ${userId} joined room: ${roomId}`);\n  console.log(`Message received at: ${ctx.receivedAt}`);\n\n  // Send confirmation (type-safe!)\n  ctx.send(UserJoined, { roomId, userId: userId || \"anonymous\" });\n});\n\nrouter.on(SendMessage, (ctx) =\u003e {\n  const { text } = ctx.payload;\n  const userId = ctx.ws.data?.userId;\n  const roomId = ctx.ws.data?.roomId;\n\n  console.log(`[${roomId}] ${userId}: ${text}`);\n\n  // Broadcast to room subscribers (type-safe!)\n  router.publish(roomId, SendMessage, { text, userId: userId || \"anonymous\" });\n});\n\n// Handle disconnections\nrouter.onClose((ctx) =\u003e {\n  const userId = ctx.ws.data?.userId;\n  const roomId = ctx.ws.data?.roomId;\n\n  if (roomId) {\n    ctx.unsubscribe(roomId);\n    // Notify others\n    router.publish(roomId, UserLeft, { userId: userId || \"anonymous\" });\n  }\n  console.log(`Disconnected: ${userId}`);\n});\n```\n\n**Context Fields:**\n\n- `ctx.payload` — Typed payload from schema (✅ fully typed!)\n- `ctx.ws.data` — Connection data (type-narrowed from `\u003cTData\u003e`)\n- `ctx.type` — Message type literal (e.g., `\"JOIN_ROOM\"`)\n- `ctx.meta` — Client metadata (correlationId, timestamp)\n- `ctx.receivedAt` — Server receive timestamp\n- `ctx.send()` — Type-safe send to this client only\n- `ctx.assignData()` — Type-safe partial data updates\n- `ctx.subscribe()` / `ctx.unsubscribe()` — Topic management\n- `ctx.error()` — Send type-safe error messages\n\n## Broadcasting and Subscriptions\n\nBroadcasting messages to multiple clients is type-safe with schema validation:\n\n```ts\nimport { z, message, createRouter } from \"@ws-kit/zod\";\n\nconst RoomUpdate = message(\"ROOM_UPDATE\", {\n  roomId: z.string(),\n  users: z.number(),\n  message: z.string(),\n});\n\nconst router = createRouter\u003c{ roomId?: string }\u003e();\n\nrouter.on(JoinRoom, (ctx) =\u003e {\n  const { roomId } = ctx.payload;\n\n  // Subscribe to room updates\n  ctx.subscribe(roomId);\n  ctx.assignData({ roomId });\n\n  console.log(`User joined: ${roomId}`);\n\n  // Broadcast to all room subscribers (type-safe!)\n  router.publish(roomId, RoomUpdate, {\n    roomId,\n    users: 5,\n    message: \"A user has joined\",\n  });\n});\n\nrouter.on(SendMessage, (ctx) =\u003e {\n  const roomId = ctx.ws.data?.roomId;\n\n  // Broadcast message to room (fully typed, no JSON.stringify needed!)\n  router.publish(roomId, RoomUpdate, {\n    roomId,\n    users: 5,\n    message: ctx.payload.text,\n  });\n});\n\nrouter.onClose((ctx) =\u003e {\n  const roomId = ctx.ws.data?.roomId;\n  if (roomId) {\n    ctx.unsubscribe(roomId);\n    router.publish(roomId, RoomUpdate, {\n      roomId,\n      users: 4,\n      message: \"A user has left\",\n    });\n  }\n});\n```\n\n**Broadcasting API:**\n\n- `router.publish(scope, schema, payload)` — Type-safe broadcast to all subscribers on a scope\n- `ctx.subscribe(topic)` — Subscribe connection to a topic (adapter-dependent)\n\n```ts\nimport { z, message, createRouter } from \"@ws-kit/zod\";\n\ntype AppData = { userId?: string; roomId?: string };\nconst router = createRouter\u003cAppData\u003e();\n\nconst JoinRoom = message(\"JOIN_ROOM\", { roomId: z.string() });\nconst UserJoined = message(\"USER_JOINED\", {\n  roomId: z.string(),\n  userId: z.string(),\n});\nconst SendMessage = message(\"SEND_MESSAGE\", {\n  roomId: z.string(),\n  message: z.string(),\n});\nconst NewMessage = message(\"NEW_MESSAGE\", {\n  roomId: z.string(),\n  userId: z.string(),\n  message: z.string(),\n});\nconst UserLeft = message(\"USER_LEFT\", { userId: z.string() });\n\nrouter.on(JoinRoom, (ctx) =\u003e {\n  const { roomId } = ctx.payload;\n  const userId = ctx.ws.data?.userId || \"anonymous\";\n\n  // Store room ID and subscribe to topic\n  ctx.assignData({ roomId });\n  ctx.subscribe(roomId);\n\n  // Send confirmation back\n  ctx.send(UserJoined, { roomId, userId });\n\n  // Broadcast to room subscribers with schema validation\n  ctx.publish(roomId, UserJoined, { roomId, userId });\n});\n\nrouter.on(SendMessage, (ctx) =\u003e {\n  const { roomId, message: msg } = ctx.payload;\n  const userId = ctx.ws.data?.userId || \"anonymous\";\n\n  console.log(`Message in room ${roomId} from ${userId}: ${msg}`);\n\n  // Broadcast the message to all room subscribers\n  ctx.publish(roomId, NewMessage, { roomId, userId, message: msg });\n});\n\nrouter.onClose((ctx) =\u003e {\n  const userId = ctx.ws.data?.userId || \"anonymous\";\n  const roomId = ctx.ws.data?.roomId;\n\n  if (roomId) {\n    ctx.unsubscribe(roomId);\n    // Notify others in the room\n    router.publish(roomId, UserLeft, { userId });\n  }\n});\n```\n\nThe `publish()` function ensures that all broadcast messages are validated against their schemas before being sent, providing the same type safety for broadcasts that you get with direct messaging.\n\n## Error handling and sending error messages\n\nEffective error handling is crucial for maintaining robust WebSocket connections. WS-Kit provides built-in error response support with standardized error codes.\n\n### Error handling with ctx.error()\n\nUse `ctx.error()` to send type-safe error responses:\n\n```ts\nimport { z, message, createRouter } from \"@ws-kit/zod\";\n\ntype AppData = { userId?: string };\nconst router = createRouter\u003cAppData\u003e();\n\nconst JoinRoom = message(\"JOIN_ROOM\", { roomId: z.string() });\n\nrouter.on(JoinRoom, async (ctx) =\u003e {\n  const { roomId } = ctx.payload;\n\n  // Check if room exists\n  const roomExists = await checkRoomExists(roomId);\n  if (!roomExists) {\n    // Send error with standardized code\n    ctx.error(\"NOT_FOUND\", `Room ${roomId} does not exist`, { roomId });\n    return;\n  }\n\n  // Continue with normal flow\n  ctx.assignData({ roomId });\n  ctx.ws.subscribe(roomId);\n});\n```\n\n### Standard error codes\n\nThe standard error codes (aligned with gRPC) are:\n\n**Terminal errors (don't retry):**\n\n- `UNAUTHENTICATED` — Authentication failed\n- `PERMISSION_DENIED` — Authenticated but lacks rights\n- `INVALID_ARGUMENT` — Invalid payload or schema mismatch\n- `FAILED_PRECONDITION` — Operation preconditions not met\n- `NOT_FOUND` — Resource not found\n- `ALREADY_EXISTS` — Resource already exists\n- `ABORTED` — Operation aborted\n\n**Transient errors (retry with backoff):**\n\n- `DEADLINE_EXCEEDED` — Request deadline exceeded\n- `RESOURCE_EXHAUSTED` — Rate limit, backpressure, or quota exceeded\n- `UNAVAILABLE` — Service temporarily unavailable\n\n**Server \u0026 evolution:**\n\n- `UNIMPLEMENTED` — Feature not implemented\n- `INTERNAL` — Server error\n- `CANCELLED` — Request cancelled by client\n\nSee [ADR-015](docs/adr/015-error-handling.md) for the complete error code taxonomy.\n\n### Custom error handling\n\nYou can add error handling middleware or lifecycle hooks:\n\n```ts\n// Error handling in connection setup\nrouter.onOpen((ctx) =\u003e {\n  try {\n    console.log(`Client ${ctx.ws.data?.clientId} connected`);\n  } catch (error) {\n    console.error(\"Error in connection setup:\", error);\n    ctx.error(\"INTERNAL\", \"Failed to set up connection\");\n  }\n});\n\n// Error handling with middleware\nrouter.use((ctx, next) =\u003e {\n  try {\n    return next();\n  } catch (error) {\n    ctx.error(\"INTERNAL\", \"Request failed\");\n  }\n});\n\n// Error handling in message handlers\nconst AuthenticateUser = message(\"AUTH\", { token: z.string() });\nrouter.on(AuthenticateUser, (ctx) =\u003e {\n  try {\n    const { token } = ctx.payload;\n    const user = validateToken(token);\n\n    if (!user) {\n      ctx.error(\"UNAUTHENTICATED\", \"Invalid authentication token\");\n      return;\n    }\n\n    // Use assignData for type-safe connection data updates\n    ctx.assignData({ userId: user.id, userRole: user.role });\n  } catch (error) {\n    ctx.error(\"INTERNAL\", \"Authentication process failed\");\n  }\n});\n```\n\n## How to compose routes\n\nOrganize code by splitting handlers into separate routers, then merge them into a main router using the `merge()` method:\n\n```ts\nimport { createRouter } from \"@ws-kit/zod\";\nimport { chatRoutes } from \"./chat\";\nimport { notificationRoutes } from \"./notification\";\n\ntype AppData = { userId?: string };\n\n// Create main router\nconst mainRouter = createRouter\u003cAppData\u003e();\n\n// Compose with sub-routers\nmainRouter.merge(chatRoutes).merge(notificationRoutes);\n```\n\nWhere `chatRoutes` and `notificationRoutes` are separate routers created with `createRouter\u003cAppData\u003e()` in their own files. The `merge()` method combines handlers, lifecycle hooks, and middleware from the composed routers.\n\n## Browser Client\n\nType-safe browser WebSocket client with automatic reconnection, authentication, and request/response patterns — using the same validator and message definitions:\n\n```ts\nimport { rpc, message, wsClient } from \"@ws-kit/client/zod\";\n\n// Define message schemas\nconst Hello = rpc(\"HELLO\", { name: z.string() }, \"HELLO_OK\", {\n  text: z.string(),\n});\nconst ServerBroadcast = message(\"BROADCAST\", { data: z.string() });\n\n// Create type-safe client with authentication\nconst client = wsClient({\n  url: \"wss://api.example.com/ws\",\n  auth: {\n    getToken: () =\u003e localStorage.getItem(\"access_token\"),\n  },\n});\n\nawait client.connect();\n\n// Send fire-and-forget message\nclient.send(Hello, { name: \"Anna\" });\n\n// Listen for server broadcasts with full type inference\nclient.on(ServerBroadcast, (msg) =\u003e {\n  // ✅ msg.payload.data is typed as string\n  console.log(\"Server broadcast:\", msg.payload.data);\n});\n\n// Request/response with auto-detected response schema (modern RPC-style)\ntry {\n  const reply = await client.request(\n    Hello,\n    { name: \"Bob\" },\n    {\n      timeoutMs: 5000,\n    },\n  );\n  // ✅ reply.payload.text is fully typed from RPC schema\n  console.log(\"Server replied:\", reply.payload.text);\n} catch (err) {\n  console.error(\"Request failed:\", err);\n}\n\n// Graceful disconnect\nawait client.disconnect();\n```\n\nYou can also use explicit response schemas for backward compatibility (traditional style):\n\n```ts\n// Traditional: client.request(schema, payload, responseSchema, options)\nconst reply = await client.request(Hello, { name: \"Bob\" }, HelloOk, {\n  timeoutMs: 5000,\n});\n```\n\n**Client Features:**\n\n- Auto-reconnection with exponential backoff\n- Configurable offline message queueing\n- Request/response pattern with timeouts\n- Built-in auth (query param or protocol header)\n- Full TypeScript type inference from schemas\n\nSee the [Client Documentation](./docs/specs/client.md) for complete API reference and advanced usage.\n\n## Breaking Changes \u0026 Migration\n\n### Validator is Required\n\nThe router now requires a validator to be configured. All imports should come from validator packages to ensure the correct validator is set up:\n\n```ts\n// ✅ Correct: Validator is included\nimport { createRouter } from \"@ws-kit/zod\";\nconst router = createRouter();\n\n// ❌ Incorrect: Will throw if no validator is set\nimport { WebSocketRouter } from \"@ws-kit/core\";\nconst router = new WebSocketRouter(); // ← Error: validator is required\n```\n\n**Migration:** Always import `createRouter()` from `@ws-kit/zod` or `@ws-kit/valibot`, not from `@ws-kit/core`.\n\n### Heartbeat is Now Opt-In\n\nHeartbeat is no longer enabled by default. Enable it explicitly if you need client liveness detection:\n\n```ts\nimport { createRouter } from \"@ws-kit/zod\";\nimport { serve } from \"@ws-kit/bun\";\n\nconst router = createRouter();\n\nserve(router, {\n  port: 3000,\n  heartbeat: {\n    intervalMs: 30_000, // Ping every 30s (default)\n    timeoutMs: 5_000, // Wait 5s for pong (default)\n    onStaleConnection(clientId, ws) {\n      console.log(`Connection ${clientId} is stale, closing...`);\n      ws.close();\n    },\n  },\n});\n```\n\n**Migration:** Add `heartbeat` config to `serve()` options if you previously relied on default heartbeat behavior.\n\n### PubSub is Lazily Initialized\n\nPubSub (for `ctx.publish()` and subscriptions) is now created only on first use. Apps without broadcasting incur zero overhead.\n\n**Migration:** No action needed. Broadcasting works the same way; initialization is just deferred.\n\n## Design \u0026 Architecture\n\nSee [Architectural Decision Records](./docs/adr/) for the core design decisions that shaped ws-kit, including type safety patterns, platform adapters, and composability.\n\n## Support\n\nQuestions or issues? Join us on [Discord](https://discord.gg/aW29wXyb7w).\n\n## Backers\n\n\u003ca href=\"https://reactstarter.com/b/1\"\u003e\u003cimg src=\"https://reactstarter.com/b/1.png\" height=\"60\" /\u003e\u003c/a\u003e\u0026nbsp;\u0026nbsp;\u003ca href=\"https://reactstarter.com/b/2\"\u003e\u003cimg src=\"https://reactstarter.com/b/2.png\" height=\"60\" /\u003e\u003c/a\u003e\u0026nbsp;\u0026nbsp;\u003ca href=\"https://reactstarter.com/b/3\"\u003e\u003cimg src=\"https://reactstarter.com/b/3.png\" height=\"60\" /\u003e\u003c/a\u003e\u0026nbsp;\u0026nbsp;\u003ca href=\"https://reactstarter.com/b/4\"\u003e\u003cimg src=\"https://reactstarter.com/b/4.png\" height=\"60\" /\u003e\u003c/a\u003e\u0026nbsp;\u0026nbsp;\u003ca href=\"https://reactstarter.com/b/5\"\u003e\u003cimg src=\"https://reactstarter.com/b/5.png\" height=\"60\" /\u003e\u003c/a\u003e\u0026nbsp;\u0026nbsp;\u003ca href=\"https://reactstarter.com/b/6\"\u003e\u003cimg src=\"https://reactstarter.com/b/6.png\" height=\"60\" /\u003e\u003c/a\u003e\u0026nbsp;\u0026nbsp;\u003ca href=\"https://reactstarter.com/b/7\"\u003e\u003cimg src=\"https://reactstarter.com/b/7.png\" height=\"60\" /\u003e\u003c/a\u003e\u0026nbsp;\u0026nbsp;\u003ca href=\"https://reactstarter.com/b/8\"\u003e\u003cimg src=\"https://reactstarter.com/b/8.png\" height=\"60\" /\u003e\u003c/a\u003e\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkriasoft%2Fws-kit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkriasoft%2Fws-kit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkriasoft%2Fws-kit/lists"}