# WSEvents

**Kind:** Interface

**Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L14)

**Part of:** [Helper](subsystem-src-helper)

WebSocket Event Listeners type

`WSEvents<T>` defines the event listener callbacks for a WebSocket connection. Each callback receives the browser event and a `WSContext<T>` instance so handlers can inspect or update connection-specific state.

## Properties

| Property | Type |
|---|---|
| `onOpen` | `(evt: Event, ws: WSContext<T>) => void` |
| `onMessage` | `(evt: MessageEvent<WSMessageReceive>, ws: WSContext<T>) => void` |
| `onClose` | `(evt: CloseEvent, ws: WSContext<T>) => void` |
| `onError` | `(evt: Event, ws: WSContext<T>) => void` |

## Diagram

```mermaid
graph LR
  WebSocket -->|open| onOpen
  WebSocket -->|message| onMessage
  WebSocket -->|close| onClose
  WebSocket -->|error| onError

  onOpen --> WSContext
  onMessage --> WSContext
  onClose --> WSContext
  onError --> WSContext
```

## Usage

```ts
import type { WSEvents } from "./helper/websocket";

type ConnectionState = {
  userId: string;
};

const events: WSEvents<ConnectionState> = {
  onOpen(_evt, ws) {
    console.log("WebSocket connected", ws);
  },

  onMessage(evt, ws) {
    console.log("Received message:", evt.data);
    console.log("Connection state:", ws);
  },

  onClose(evt, ws) {
    console.log("WebSocket closed:", evt.code, evt.reason);
    console.log("Connection state:", ws);
  },

  onError(evt, ws) {
    console.error("WebSocket error:", evt);
    console.log("Connection state:", ws);
  },
};
```

## AI Coding Instructions

- Keep each handler compatible with its declared browser event type and the shared `WSContext<T>` type.
- Read incoming payloads from `evt.data` in `onMessage`; do not assume the payload format without checking `WSMessageReceive`.
- Use `onClose` to handle close codes and cleanup related connection state.
- Use `onError` for logging or recovery logic, but do not assume it includes close details.
- Pass the `WSEvents<T>` object to the WebSocket setup code that accepts event listeners.
