Overview
Hono’s WebSocket helper is a wrapper that works across different runtimes (Cloudflare Workers, Deno, Bun, etc.) by abstracting WebSocket implementation details.The WebSocket helper itself doesn’t implement WebSockets. You need to use runtime-specific adaptors that implement the
upgradeWebSocket function.Adaptors
Use runtime-specific adaptors:- Cloudflare Workers:
hono/cloudflare-workers - Deno:
hono/deno - Bun:
hono/bun - Node.js: Third-party adaptor needed
Import
Basic Usage
Simple WebSocket Server
Client-Side Connection
Event Handlers
The WebSocket helper provides four event handlers:onOpen
Called when the connection is established:onMessage
Called when a message is received:onClose
Called when the connection closes:onError
Called when an error occurs:WSContext
Thews parameter in event handlers is a WSContext instance:
send()
Send data to the client:close()
Close the connection:number
default:"1000"
Close code (1000 = normal closure)
string
Human-readable close reason
readyState
Get the connection state:url
Access the connection URL:protocol
Get the negotiated subprotocol:raw
Access the underlying WebSocket:Advanced Usage
Chat Server Example
Using Context Data
Access Hono context inside WebSocket handlers:Binary Data
Handle binary messages:Direct Upgrade
Upgrade in a handler directly:Testing WebSockets
Test WebSocket endpoints:Creating Custom Adaptors
Create a custom WebSocket adaptor:Close Codes
Standard WebSocket close codes:Normal Closure
Successful operation / regular socket shutdown
Going Away
Browser tab closed or server is shutting down
Protocol Error
Endpoint received a malformed frame
Unsupported Data
Endpoint received data it cannot accept
Abnormal Closure
No close frame received (connection lost)
Invalid Data
Endpoint received inconsistent message
Policy Violation
Endpoint received message violating policy
Message Too Big
Message is too big to process
Internal Error
Server encountered an unexpected condition
Use Cases
Real-time Chat
Build chat applications with instant message delivery
Live Updates
Push live data updates to connected clients
Gaming
Real-time multiplayer game state synchronization
Collaboration
Collaborative editing and presence features
Best Practices
Always handle connection cleanup in
onClose and onError to prevent memory leaks.For one-way server-to-client communication, consider using Server-Sent Events (SSE) instead, which is simpler and works over HTTP.
Comparison with SSE
Choose WebSocket when you need bidirectional communication. Use SSE for simpler server-to-client streaming.