Modern Node.js provides a built-in WebSocket client, so applications can connect to WebSocket servers without installing a separate client library for basic use cases.
WebSockets keep one connection open so the client and server can exchange messages in both directions. They are useful for live dashboards, notifications, chat, device telemetry, and other real-time features.
Use Node.js 22.4 or later for the stable built-in client. You still need a real WebSocket server; wss://example.com/socket below is a placeholder, not a working echo service.
Create a WebSocket
Example:
const socket = new WebSocket('wss://example.com/socket');
Use wss:// for an encrypted WebSocket connection.
Wait for the Connection
Example:
socket.addEventListener('open', () => {
console.log('Connected');
});
The open event fires after the WebSocket handshake succeeds.
Send a Message
Example:
socket.addEventListener('open', () => {
socket.send(JSON.stringify({
type: 'subscribe',
channel: 'prices'
}));
});
WebSocket messages can contain text or binary data. JSON is a common application-level format for text messages.
Receive Messages
Example:
socket.addEventListener('message', event => {
console.log('Received:', event.data);
});
Always validate incoming data before assuming it matches the format your application expects.
Handle Errors
Example:
socket.addEventListener('error', event => {
console.error('WebSocket error');
});
The error event tells you the connection encountered a problem, but applications often need additional state or logging to decide whether to reconnect.
Handle Closure
Example:
socket.addEventListener('close', event => {
console.log('Closed:', event.code, event.reason);
});
Close the Connection
Call this from the part of your application that has finished its work, not immediately after constructing the socket:
Example:
if (socket.readyState === WebSocket.OPEN) {
socket.close(1000, 'Finished');
}
Status code 1000 represents a normal closure.
Ready States
| State | Meaning |
|---|---|
| CONNECTING | The connection is being established |
| OPEN | Messages can be sent and received |
| CLOSING | The close handshake is in progress |
| CLOSED | The connection is closed |
Reconnection
The WebSocket API does not automatically reconnect. If reconnecting is appropriate, add backoff and a retry limit so an outage does not create a tight reconnect loop.
Do not treat every disconnect as an error. Mobile networks, server deployments, idle timeouts, and normal shutdowns can all close a WebSocket.
Conclusion
The built-in Node.js WebSocket client covers the core client workflow: connect, wait for open, send and receive messages, react to errors, and close cleanly. Add validation and reconnection logic according to the needs of your application.