WebSocket lifecycle
Local baseline: Node.js 22.16.0, ECMAScript modules, synthetic data. Run each complete example independently as node main.mjs in a disposable directory. Static ByteMind blocks do not imply live Node execution. SQLite is experimental in this baseline. Third-party integrations below are staged candidates, not installed or validated dependencies.
Observe client state constants
console.log(typeof WebSocket);console.log([WebSocket.CONNECTING,WebSocket.OPEN,WebSocket.CLOSING,WebSocket.CLOSED].join(','));Expected output:
function0,1,2,3These constants are observed in the installed Node client API; no connection is opened.
How it works
A client moves through CONNECTING, OPEN, CLOSING and CLOSED. Wait for open before sending, handle errors, and release resources on close. A heartbeat can detect a dead peer; reconnect should use bounded exponential delay with jitter in deployed systems. Reconnect creates a new connection, so restore subscriptions only after authorization. Validate message type and length, cap peers and pending bytes. Browsers cannot freely attach arbitrary headers in the WebSocket constructor; choose an appropriate authentication mechanism and check Origin for browser cookie-based sessions. TLS is required for production confidentiality.
Model a bounded reconnect policy
function nextDelay(attempt) {return attempt>=4?null:Math.min(8000,500*2**attempt);}console.log(JSON.stringify([0,1,2,3,4].map(nextDelay)));Expected output:
[500,1000,2000,4000,null]Four scheduled retries have explicit delays; null means stop. Production jitter is omitted for deterministic reasoning.
Bounded loopback WebSocket exchange
NOT RUN — ws (8.x candidate; no dependency installed; require an external 5-second process timeout). This integration requires reviewed pinned dependencies and a disposable fixture. Do not execute against shared services.
import {WebSocketServer} from 'ws';import {once} from 'node:events';const server = new WebSocketServer({host:'127.0.0.1',port:0,maxPayload:128});let client;try { await once(server,'listening'); server.once('connection',peer=>peer.once('message',data=>{if(data.toString()==='hello') peer.send('welcome');else peer.close(1008);})); client=new WebSocket(`ws://127.0.0.1:${server.address().port}`); await once(client,'open',{signal:AbortSignal.timeout(1000)}); const message=once(client,'message',{signal:AbortSignal.timeout(1000)}); client.send('hello'); console.log((await message)[0].data);} finally { client?.close(); for(const peer of server.clients)peer.terminate(); await new Promise(resolve=>server.close(resolve));}Intended result (not observed): welcome
Common mistakes
Do not assume send implies delivery or persistence. Avoid infinite immediate reconnection. A state model is not a WebSocket protocol test; use a real compatible server and client for handshake and message assertions.
Practice and next steps
Trace a disconnect after an acknowledged message and before another acknowledgment. Decide which application messages need replay or deduplication and how a client knows when to stop reconnecting.
Further reading: https://github.com/websockets/ws. Related staged reference: node-websocket-lifecycle-lookup (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
WebSocket lifecycle — knowledge check
Apply the lesson to a fresh scenario and identify the failure boundary.
When should ordinary messages be sent?
What does a successful send call guarantee?
What should a reconnect policy include?