Skip to main content
The WebSocket Helper provides a platform-agnostic API for handling WebSocket connections in Hono applications.

Import

Core Concepts

The WebSocket helper uses an adapter pattern to support different runtime environments (Cloudflare Workers, Deno, Bun, Node.js).

Functions

defineWebSocketHelper()

Creates a platform-specific WebSocket upgrade function.
WebSocketHelperDefineHandler<T, U>
required
Function that handles the WebSocket upgrade for a specific platform.
UpgradeWebSocket<T, U>
An upgrade function that can be used as middleware or called directly
Example

Classes

WSContext

Provides a unified API for controlling WebSocket connections.
WSContextInit<T>
required
Initialization object:
  • send: Function to send data
  • close: Function to close connection
  • readyState: Current connection state
  • raw: Optional raw WebSocket object
  • url: Optional WebSocket URL
  • protocol: Optional WebSocket protocol
Methods:

send()

Sends data through the WebSocket.
string | ArrayBuffer | Uint8Array
required
Data to send
SendOptions
Send options:
  • compress: Enable compression (boolean)

close()

Closes the WebSocket connection.
number
Close status code (default: 1000)
string
Close reason message
Properties:
  • readyState: Current state (0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED)
  • raw: Access to platform-specific WebSocket object
  • url: WebSocket connection URL
  • protocol: Selected WebSocket sub-protocol
  • binaryType: Binary data type (default: ‘arraybuffer’)

Types

WSEvents

Event handlers for WebSocket lifecycle.
(evt: Event, ws: WSContext<T>) => void
Called when connection is established
(evt: MessageEvent, ws: WSContext<T>) => void
Called when message is received
(evt: CloseEvent, ws: WSContext<T>) => void
Called when connection is closed
(evt: Event, ws: WSContext<T>) => void
Called when an error occurs

UpgradeWebSocket

Type for the WebSocket upgrade function.

WSReadyState

WebSocket connection state.

Usage with Runtime Adapters

Cloudflare Workers

Deno

Bun

Examples

Chat Room

Real-time Data Stream

Authenticated WebSocket

Binary Data

Connection State Tracking

Platform Support

The WebSocket helper supports multiple runtimes through platform-specific implementations:
  • Cloudflare Workers: hono/cloudflare-workers
  • Deno: hono/deno
  • Bun: hono/bun
  • Node.js: Via adapters like @hono/node-server
Each platform provides its own upgradeWebSocket function that implements the unified API.