{"id":20289917,"url":"https://github.com/thanhhoajs/websocket","last_synced_at":"2026-02-20T17:31:41.311Z","repository":{"id":246757444,"uuid":"822669644","full_name":"thanhhoajs/websocket","owner":"thanhhoajs","description":"@thanhhoajs/websocket is a powerful WebSocket library built on top of Bun's native WebSocket implementation.","archived":false,"fork":false,"pushed_at":"2024-08-10T14:06:52.000Z","size":72,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-09-06T09:52:40.834Z","etag":null,"topics":["thanhhoajs","websocket"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/@thanhhoajs/websocket","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/thanhhoajs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-07-01T15:17:54.000Z","updated_at":"2025-08-01T04:28:17.000Z","dependencies_parsed_at":null,"dependency_job_id":"ad018359-99f1-4a30-be57-5830a728c9f3","html_url":"https://github.com/thanhhoajs/websocket","commit_stats":null,"previous_names":["thanhhoajs/websocket"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/thanhhoajs/websocket","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thanhhoajs%2Fwebsocket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thanhhoajs%2Fwebsocket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thanhhoajs%2Fwebsocket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thanhhoajs%2Fwebsocket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thanhhoajs","download_url":"https://codeload.github.com/thanhhoajs/websocket/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thanhhoajs%2Fwebsocket/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29658373,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-20T16:33:43.953Z","status":"ssl_error","status_checked_at":"2026-02-20T16:33:43.598Z","response_time":59,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"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":["thanhhoajs","websocket"],"created_at":"2024-11-14T15:05:29.214Z","updated_at":"2026-02-20T17:31:41.297Z","avatar_url":"https://github.com/thanhhoajs.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://drive.google.com/uc?export=view\u0026id=1_M5tYoaKfXpqsOAPQl3WVWs9u5NWrG76\" alt=\"ThanhHoa Logo\" width=\"300\"/\u003e\n\u003c/p\u003e\n\n# @thanhhoajs/websocket\n\nA high-performance, feature-rich WebSocket library supercharging Bun's native WebSocket implementation. Designed for developers who demand speed, flexibility, and ease of use in their real-time applications.\n\n@thanhhoajs/websocket seamlessly blends the raw power of Bun's WebSocket with an intuitive API, bringing you the best of both worlds. Whether you're building a chat application, a live dashboard, or a complex real-time system, this library provides the tools you need to create robust, scalable WebSocket servers with minimal effort.\n\nKey highlights:\n\n- 🚀 Lightning-fast performance leveraging Bun's speed\n- 🛠 Intuitive routing and middleware system\n- 📡 Built-in pub/sub functionality for effortless broadcasting\n- 🔒 TypeScript support for type-safe development\n- 🎛 Fine-grained control over WebSocket lifecycle events\n- 🧩 Easily extensible for custom use cases\n\nEmbrace the future of real-time web applications with @thanhhoajs/websocket – where performance meets developer productivity.\n\n## Features\n\n- **High Performance**: Built on Bun's native WebSocket implementation for optimal speed and efficiency\n- **Easy Setup**: Simple API to quickly create and configure WebSocket servers\n- **Routing System**: Flexible routing mechanism to handle different WebSocket endpoints\n- **Middleware Support**: Global and route-specific middleware for customizable request/message processing\n- **Event-Driven Architecture**: Built-in event system for easy handling of WebSocket lifecycle events\n- **Grouping Routes**: Ability to group routes with common prefixes for better organization\n- **Pub/Sub Functionality**: Built-in publish/subscribe system for efficient message broadcasting\n- **Type Safety**: Full TypeScript support for enhanced developer experience and code reliability\n- **Custom Data Handling**: Support for attaching custom data to WebSocket connections\n- **Flexible Message Types**: Handle string, Buffer, and various ArrayBuffer types for messages\n- **Header Validation**: Option to validate headers before upgrading to WebSocket connection\n- **Query and Param Parsing**: Automatic parsing of URL query parameters and route params\n- **Broadcast Capability**: Easily send messages to all connected clients\n- **Topic-Based Communication**: Subscribe clients to specific topics and publish messages to those topics\n- **Connection Management**: Methods to handle WebSocket connections, including subscription status checks\n- **Graceful Shutdown**: Ability to stop the WebSocket server cleanly\n- **Server Statistics**: Access to server stats like pending connections and route count\n- **Compression Support**: Option to compress messages for reduced bandwidth usage\n- **Customizable Serve Options**: Flexible configuration options inherited from Bun's WebSocket serve options\n- **Error Handling**: Built-in error handling and event emission for various WebSocket scenarios\n- **Extensibility**: Easy to extend and integrate with other parts of your application\n- **Low Memory Footprint**: Efficient memory usage, ideal for high-concurrency scenarios\n- **Cross-Platform**: Works on any platform supported by Bun\n- **Open Source**: MIT licensed for use in both personal and commercial projects\n\n## Installation\n\nMake sure you have Bun installed (version 1.0.0 or later). Then, you can install the package using:\n\n```bash\nbun add @thanhhoajs/websocket\n```\n\n## Quick Start\n\nHere's a simple example of how to use ThanhHoaWebSocket:\n\n```typescript\nimport { ThanhHoaWebSocket, RouterHandler } from '@thanhhoajs/websocket';\n\nconst ws = new ThanhHoaWebSocket({ port: 3000 });\nconst router = new RouterHandler();\n\nrouter.route('chat', {\n  onOpen: (ws, query, params) =\u003e {\n    console.log('New connection');\n    ws.send('Welcome to the chat!');\n  },\n  onMessage: (ws, message) =\u003e {\n    console.log(`Received: ${message}`);\n    ws.send(`You said: ${message}`);\n  },\n  onClose: (ws, code, reason) =\u003e {\n    console.log(`Connection closed: ${code} - ${reason}`);\n  },\n});\n\nws.group('', router);\n\n// Logger\nws.logger();\n\nconsole.log(`WebSocket server is running on ws://localhost:${ws.port}`);\n```\n\n## Advanced Usage\n\nHere's an example showcasing more advanced features of ThanhHoaWebSocket, including middleware, grouping, pub/sub functionality, and custom data handling:\n\n```typescript\nimport {\n  ThanhHoaWebSocket,\n  RouterHandler,\n  type WebSocketMiddleware,\n  type IThanhHoaWebSocketData,\n} from '@thanhhoajs/websocket';\nimport type { ServerWebSocket } from 'bun';\n\n// Create a new WebSocket server\nconst ws = new ThanhHoaWebSocket({ port: 3000 });\nconst router = new RouterHandler();\n\n// Define a middleware\nconst authMiddleware: WebSocketMiddleware = async (\n  ws: ServerWebSocket\u003cIThanhHoaWebSocketData\u003e,\n) =\u003e {\n  const token = ws.data.headers.get('Authorization');\n  if (!token) {\n    ws.close(1008, 'Unauthorized');\n    return false;\n  }\n  // Perform token validation here\n  ws.data.custom = { userId: 'user123' }; // Attach custom data\n  return true;\n};\n\n// Define route handlers\nconst chatHandler = {\n  onOpen: (\n    ws: ServerWebSocket\u003cIThanhHoaWebSocketData\u003e,\n    query?: Record\u003cstring, string\u003e,\n  ) =\u003e {\n    console.log(`New chat connection. User ID: ${ws.data.custom?.userId}`);\n    ws.subscribe('general'); // Subscribe to 'general' topic\n    ws.send('Welcome to the chat!');\n  },\n  onMessage: (\n    ws: ServerWebSocket\u003cIThanhHoaWebSocketData\u003e,\n    message: string | Buffer,\n  ) =\u003e {\n    console.log(`Received: ${message}`);\n    ws.publish('general', `User ${ws.data.custom?.userId} says: ${message}`);\n  },\n  onClose: (\n    ws: ServerWebSocket\u003cIThanhHoaWebSocketData\u003e,\n    code: number,\n    reason: string,\n  ) =\u003e {\n    console.log(`Chat connection closed: ${code} - ${reason}`);\n  },\n};\n\n// Add routes\nrouter.route('chat', authMiddleware, chatHandler);\n\n// Group routes\nws.group('api', authMiddleware, router);\n\n// Global error handling\nws.on('error', (error, ws) =\u003e {\n  console.error('WebSocket error:', error);\n  ws.close(1011, 'Internal Server Error');\n});\n\n// Broadcast server status every 5 seconds\nsetInterval(() =\u003e {\n  const stats = ws.getStats();\n  ws.broadcast(JSON.stringify({ type: 'serverStatus', data: stats }));\n}, 5000);\n\nconsole.log(\n  `Advanced WebSocket server is running on ws://localhost:${ws.port}`,\n);\n```\n\nThis advanced example demonstrates:\n\n1. Using middleware for authentication\n2. Custom header validation\n3. Attaching and using custom data on WebSocket connections\n4. Implementing pub/sub with topics\n5. Grouping routes with a common prefix\n6. Global error handling\n7. Broadcasting server statistics to all clients\n8. Using the event emitter for custom events\n\n## API Overview\n\n### ThanhHoaWebSocket\n\nThe main class for creating and managing a WebSocket server.\n\n- `constructor(options: ThanhHoaWebSocketOptions)`: Creates a new WebSocket server\n- `use(middleware: WebSocketMiddleware)`: Adds a global middleware\n- `group(prefix: string, ...args: (WebSocketMiddleware | RouterHandler)[])`: Groups routes with a common prefix\n- `broadcast(message: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, compress?: boolean)`: Sends a message to all connected clients\n- `subscribe(ws: ServerWebSocket, topic: string)`: Subscribes a client to a topic\n- `publish(ws: ServerWebSocket, topic: string, message: string | Bun.BufferSource, compress?: boolean)`: Publishes a message to a topic\n\n### RouterHandler\n\nManages WebSocket routes.\n\n- `route(path: string, ...args: (WebSocketMiddleware | IWebSocketRouteHandler)[])`: Adds a new route\n\n## Performance\n\nThanhHoaWebSocket is built for high performance. In our benchmarks:\n\n```\nTime to connect 16 WebSockets: 9.73ms\nTime to send and receive 1,000,000 messages: 5990.51ms\n```\n\n### Benchmark Details\n\n- **Connections**: 16 WebSocket connections\n- **Messages**: 62500 messages per connection (1,000,000 total)\n- **Environment**: [R7 8845H, 32GB 7500MHz, AMD Radeon 780M]\n\n### Interpretation\n\n- The library can establish 16 WebSocket connections in just 9.73ms, demonstrating fast connection handling.\n- It can process 1,000,000 messages (send and receive) in 5990.51ms, showing high throughput capabilities.\n\n## Author\n\nNguyen Nhu Khanh \u003ckwalker.nnk@gmail.com\u003e\n\n## License\n\n[MIT License](https://github.com/thanhhoajs/websocket?tab=MIT-1-ov-file)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthanhhoajs%2Fwebsocket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthanhhoajs%2Fwebsocket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthanhhoajs%2Fwebsocket/lists"}