Node.js Reference ยท Web APIs in Node.js
Node.js WebSocket client
Reference for the global WebSocket client in Node.js: connect, send text and binary messages, handle open, message, error and close events.
WebSocket is a global class that opens a two-way connection to a WebSocket server. It follows the browser standard: you create it with a ws:// or wss:// URL, wait for the open event, then call send() and listen for message events until one side closes the connection.
Node has only the client. There is no built-in WebSocket server, so a server needs a package such as ws, or your own code on top of the http module's upgrade event. The examples below include a tiny echo server for loopback, enough for text messages. The client is stable since Node 22 and is built on undici.
const socket = new WebSocket('ws://localhost:8080'); socket.addEventListener('open', () => socket.send('hello')); socket.addEventListener('message', (event) => console.log(event.data));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
new WebSocket(url[, protocols])
| Name | Description |
|---|---|
url |
A ws:// or wss:// URL (http:// and https:// are accepted and converted, as in browsers). No fragment allowed. |
protocols |
A subprotocol string or an array of them, offered in Sec-WebSocket-Protocol. |
Node also accepts an options object as the second argument, with protocols, dispatcher and headers; the headers option is a Node/undici extension (browsers cannot set handshake headers).
| Member | Description |
|---|---|
readyState |
0 CONNECTING, 1 OPEN, 2 CLOSING, 3 CLOSED (also as WebSocket.CONNECTING and so on). |
url, protocol, extensions |
The normalized URL, the subprotocol the server picked ('' if none) and the negotiated extensions. |
bufferedAmount |
Bytes queued by send() but not yet written. |
binaryType |
'blob' (default) or 'arraybuffer': the type of binary event.data. |
send(data) |
Send a string, Blob, ArrayBuffer or typed array. |
close([code[, reason]]) |
Start the closing handshake. code must be 1000 or 3000 to 4999; reason at most 123 bytes of UTF-8. |
onopen, onmessage, onerror, onclose |
Handler properties; addEventListener() works as well. |
Events: open, message (a MessageEvent with data), error and close (a CloseEvent with code, reason and wasClean).
Errors: an invalid URL throws SyntaxError (DOMException); asking for duplicate or illegal subprotocols also throws SyntaxError. send() while CONNECTING throws InvalidStateError. close() with a bad code throws InvalidAccessError. Connection failures are reported through error and then close (code 1006), not by exceptions, and the error event carries no details.
Usage notes
- Wait for
openbeforesend(). A common pattern is to queue messages in an array until the socket is open. - Check
bufferedAmountbefore sending big streams of data; the socket does not apply back-pressure for you. - Binary data arrives as
Blobby default. Setsocket.binaryType = 'arraybuffer'before the first message if you want typed arrays. - There is no automatic reconnect, ping or pong API. Browsers and Node answer server pings for you, but you must implement reconnection (with backoff) and application-level heartbeats yourself.
- Close codes:
1000normal,1001going away,1005no status code in the close frame (never sent on the wire),1006abnormal (connection lost without a close frame, also never sent),1008policy violation,1011server error. Choose codes from 3000 to 4999 for your own meaning. - A pending socket keeps the process alive until it closes. Always close sockets, or the script will not exit.
wss://uses the system's trusted certificates (andNODE_EXTRA_CA_CERTSif set); there is no option to skip verification in the standard API.- The
wspackage is still useful for servers, for compression options, for sending custom headers on older Node versions, and for streaming large messages.