undici exports aDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/nodejs/undici/llms.txt
Use this file to discover all available pages before exploring further.
WebSocket class that implements the WHATWG WebSocket API, enabling bidirectional communication from Node.js without browser restrictions. It also exports an experimental WebSocketStream for stream-based WebSocket access and a ping() utility for keepalive frames.
WebSocket
Constructor
The WebSocket server URL. Must use
ws:// or wss:// scheme.Optional. A subprotocol string, array of subprotocols, or a
WebSocketInit object for advanced configuration.WebSocketInit options
When passing an object as the second argument:Subprotocol(s) to request the server use.
A custom dispatcher (e.g.
ProxyAgent, Agent) to use for the WebSocket handshake connection.Custom headers to include in the WebSocket handshake HTTP request.
Basic usage
Basic WebSocket connection
Using a custom dispatcher
Pass aWebSocketInit object to use a custom dispatcher such as ProxyAgent:
WebSocket through a proxy
The
WebSocketInit object form is a Node.js extension — it will not work in browsers or other platforms that don’t allow passing an object as the second argument.Subprotocols (standard form)
If you don’t need a custom dispatcher, use the standard string/array form:WebSocket over HTTP/2
WebSocket over HTTP/2
Sending data
Sending text and binary
Receiving binary data
SetbinaryType to control how binary messages are delivered:
readyState constants
| Constant | Value | Description |
|---|---|---|
WebSocket.CONNECTING | 0 | Connection not yet established |
WebSocket.OPEN | 1 | Connection is open and ready |
WebSocket.CLOSING | 2 | Connection is closing |
WebSocket.CLOSED | 3 | Connection is closed |
Closing connections
ping()
Theping() function sends a WebSocket ping frame for keepalive or connection verification.
The WebSocket instance to send the ping frame on.
Optional payload data. Must not exceed 125 bytes. The server must respond with a pong containing the same payload.
Using ping for keepalive
ping() only sends if the WebSocket is in the OPEN state. Payloads must not exceed 125 bytes.WebSocketStream
WebSocketStream provides a stream-based interface to WebSocket connections using WHATWG Streams (readable/writable).