[]previous and next page

WebSocketHandlers

The handlers of a WebSocket route.

The handlers of a WebSocket route.

Import#

ts
import type { WebSocketHandlers } from "@shadow-js/dusk/server";

Signature#

ts
interface WebSocketHandlers {
  /**
   * Runs before the handshake answers. Return a `Response` to refuse the connection (a 401 for a missing
   * session, say); return nothing to accept it. The event carries the request's cookies, so a session
   * is read here. Anything it stores on `event` is not kept: copy what the connection needs into
   * `ws.data` in `open`.
   */
  upgrade?(event: RequestEvent): Response | undefined | void | Promise<Response | undefined | void>;
  /** Runs once the connection is open. Failure closes it with 1011. */
  open?(ws: WebSocketConnection, event: RequestEvent): void | Promise<void>;
  /** Runs for each message: text as a string, binary as bytes. Failure closes the connection with 1011. */
  message?(
    ws: WebSocketConnection,
    message: string | Uint8Array,
    event: RequestEvent,
  ): void | Promise<void>;
  /** Runs once when the connection closes, with the close code and reason. */
  close?(
    ws: WebSocketConnection,
    code: number,
    reason: string,
    event: RequestEvent,
  ): void | Promise<void>;
  /** Runs for a protocol violation or a failed handler, before the connection closes. */
  error?(ws: WebSocketConnection, error: unknown, event: RequestEvent): void | Promise<void>;
}

Members#

Name Type Description
upgrade? upgrade?(event: RequestEvent): Response | undefined | void | Promise<Response | undefined | void> Runs before the handshake answers. Return a Response to refuse the connection (a 401 for a missing session, say); return nothing to accept it. The event carries the request's cookies, so a session is read here. Anything it stores on event is not kept: copy what the connection needs into ws.data in open.
open? open?(ws: WebSocketConnection, event: RequestEvent): void | Promise<void> Runs once the connection is open. Failure closes it with 1011.
message? message?( ws: WebSocketConnection, message: string | Uint8Array, event: RequestEvent, ): void | Promise<void> Runs for each message: text as a string, binary as bytes. Failure closes the connection with 1011.
close? close?( ws: WebSocketConnection, code: number, reason: string, event: RequestEvent, ): void | Promise<void> Runs once when the connection closes, with the close code and reason.
error? error?(ws: WebSocketConnection, error: unknown, event: RequestEvent): void | Promise<void> Runs for a protocol violation or a failed handler, before the connection closes.