Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 133 ยท Networking and HTTP

WebSockets

Learn WebSockets in Node.js - the HTTP upgrade handshake and Sec-WebSocket-Accept, frame format, the built-in WebSocket client, a hand-written server, ping/pong, close codes, plus the ws library and Socket.IO.

HTTP is a conversation where the client always speaks first: it asks, the server answers. That is awkward for a chat, a multiplayer game or a live document, where either side may have news at any moment. Server-Sent Events let the server push, but the client still needs separate requests to talk back. A WebSocket is a single long-lived connection over which both sides can send messages whenever they like, with very little overhead per message.

In this lesson you will see how a WebSocket starts life as an ordinary HTTP request, what the bytes of a message look like, how to use Node's built-in WebSocket client, and how to write a small but correct server by hand using only node:http and node:crypto. Writing it once removes the mystery from libraries such as ws and Socket.IO, which we cover at the end. You should be comfortable with TCP Servers and Clients with net and The http Module: Servers, and with Buffers for the byte work.

The handshake: HTTP says "upgrade"

A WebSocket connection begins as a normal GET request that asks to switch protocols:

TEXT
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

If the server agrees, it answers 101 Switching Protocols, and from the next byte on the same TCP connection speaks the WebSocket protocol instead of HTTP:

TEXT
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

The Sec-WebSocket-Accept value proves that the server really understands WebSockets (and is not a confused HTTP server echoing headers). The rule: take the client's key, append the fixed GUID 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, hash the result with SHA-1, and encode the digest in base64. SHA-1 is fine here because this is not a security signature, just a handshake check.

Node.js Computing Sec-WebSocket-Accept

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.

The first line must equal the value in the specification example above, which confirms the recipe. Node exposes the switch through the 'upgrade' event of an http.Server: if you have a listener for it, Node hands you the raw socket instead of building a ServerResponse. Let us watch a real handshake from the client side with http.request, which emits the same event for a 101 answer.

Node.js A raw upgrade request

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.

That is the entire handshake. A browser would also send an Origin header; your server should check it against an allow-list, because WebSockets are not covered by the same-origin policy and a malicious page can open a connection to your server using the visitor's cookies ("cross-site WebSocket hijacking").

Frames: how messages look on the wire

After the handshake, data travels in frames. A frame begins with a small header:

  • Byte 1: the FIN bit (1 = last frame of the message) and a 4-bit opcode: 0x1 text, 0x2 binary, 0x8 close, 0x9 ping, 0xA pong, 0x0 continuation.
  • Byte 2: the MASK bit and a 7-bit length. If the length is 0 to 125 it is the payload size. The value 126 means "the next 2 bytes hold the length" and 127 means "the next 8 bytes".
  • A 4-byte masking key, present only when MASK is set.
  • The payload, XOR-ed byte by byte with the masking key when masked.

Frames from the client to the server must be masked; frames from the server to the client must not be. The mask is not encryption: it only prevents tricks against badly behaved proxies. Let us write an encoder and a decoder and look at the bytes. The decoder returns the frames it can complete and the leftover bytes, because a TCP read may contain half a frame or three frames.

Node.js Encoding and decoding WebSocket frames

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.

The first frame is 81024869 in hex: 81 means FIN plus text opcode, 02 the length and then the two bytes of Hi. The header is 2 bytes for payloads up to 125 bytes, 4 bytes up to 65,535 and 10 bytes beyond: WebSockets are very cheap for small messages compared with HTTP requests, which repeat hundreds of bytes of headers. In the last test the length is 5, not 4, because it counts UTF-8 bytes.

The built-in WebSocket client

Since Node 22 a standard WebSocket class is available globally, with the same API as the browser's. You create it with a ws:// (or wss:// for TLS) URL and attach handlers: open, message, error and close. Its readyState is 0 (connecting), 1 (open), 2 (closing) or 3 (closed). send() accepts strings, Buffers and typed arrays.

A minimal server from scratch

Now put everything together. This server handles 'upgrade', validates the handshake, parses frames from the socket, answers pings, enforces a maximum message size, performs the closing handshake, and broadcasts every text message to all connected clients (a mini chat room). The example uses the same encodeFrame/decodeFrames functions as above, repeated so that it is self-contained.

Node.js A hand-written WebSocket chat server

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.

Study how the pieces fit. The 'upgrade' handler writes the 101 response itself, so the socket is now a raw duplex stream. pending accumulates bytes because TCP does not respect message boundaries. The close frame echoes the code the client sent, completing the closing handshake; abnormal drops (a killed process, a lost connection) surface on the client as close code 1006 with no handshake. The common close codes are 1000 normal, 1001 going away, 1002 protocol error, 1003 unsupported data, 1007 invalid payload, 1008 policy violation, 1009 message too big, 1011 server error.

This server is a teaching tool. It ignores fragmented messages (FIN = 0 with continuation frames), UTF-8 validation of text frames, 64-bit lengths beyond rejecting them, extensions like permessage-deflate, and back-pressure when a client reads slowly. A production library handles all of these, which is why you should use one.

Ping, pong and detecting dead connections

A TCP connection can look open for minutes after the other side vanished (a laptop lid closed, a phone left Wi-Fi). WebSockets have built-in ping and pong control frames for this. Typical servers send a ping every 20 to 30 seconds and terminate sockets that did not answer the previous one. Browsers answer pings automatically; the standard client API cannot send pings, so applications that need liveness checks from the client also send a small application-level message such as {"type":"ping"}. Our server above already answered pings by writing a pong with the same payload.

Reconnecting clients

Connections will break, so clients should reconnect with exponential backoff (wait 0.5 s, 1 s, 2 s, ... up to a limit, plus random jitter so that thousands of clients do not stampede the server after an outage), and re-send whatever state the server needs. The code below tests the logic against a server that rejects every upgrade. When the handshake fails, the client gets an error event and then close with code 1006.

Node.js Reconnect with backoff (server refuses on purpose)

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.

The delays printed are the exponential schedule 10, 20, 40 and 80 ms (real applications start near half a second). Abnormal closes always report code 1006, because the handshake never finished: that code is never sent by anyone, it is only reported locally.

Security checklist

  • Check Origin during the upgrade (reject unknown origins with 403) when cookies authenticate users.
  • Authenticate during the handshake, with a cookie or a short-lived token in a header or query string. Do not accept a connection first and "authenticate later". Query-string tokens end up in logs, so keep them short-lived.
  • Use wss:// (TLS) in production; plain ws:// is readable and tamperable by anyone on the path.
  • Limit message size, rate and connections per client, and validate every message like any other input (Web Application Security).
  • Never trust message content: parse JSON in try/catch, check types, escape output.

The ws library and Socket.IO (read-only)

In real projects you do not write the protocol yourself. The most popular library is ws, which is fast, complete and the base of many others. Our editor has no npm packages, so the code below is for reading only. Notice how closely it mirrors what we built:

JavaScript
// npm install ws   (read-only example, not runnable in our editor)
import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (socket, request) => {
  socket.on('message', (data, isBinary) => {
    // broadcast to everyone else
    for (const client of wss.clients) {
      if (client !== socket && client.readyState === 1) {
        client.send(data, { binary: isBinary });
      }
    }
  });
  socket.on('close', (code, reason) => console.log('closed', code));
});

ws also handles fragmentation, compression, ping/pong helpers (socket.ping()), back-pressure (socket.bufferedAmount) and can attach to an existing HTTP server with new WebSocketServer({ server }) or noServer: true if you want to do your own authentication in the 'upgrade' handler.

Socket.IO is a different thing: a library with its own protocol on top of WebSockets (with an HTTP long-polling fallback). It adds named events with acknowledgements, rooms and namespaces, automatic reconnection, and a Redis adapter for several servers. A Socket.IO client cannot talk to a plain WebSocket server and the other way round. Choose it when you want those features ready-made and accept the extra weight; choose plain WebSockets (via ws or the platform's WebSocket) for interoperability with browsers and other languages.

Scaling WebSockets

Every connection is a long-lived socket held in memory, so one process can hold tens of thousands of idle connections but each needs a heartbeat. With several servers, a message from a client on server A must reach clients on server B, which needs a shared channel such as Redis pub/sub or a message broker. Load balancers need to support the Upgrade header and use long idle timeouts. During deployments, tell clients to reconnect gradually by closing with 1001 ("going away"). More in Cluster, Scaling and Load Balancing and Real-Time, Queues and the Wider Ecosystem; the chat project is built in Project: Real-Time Chat Server.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the server send to accept a WebSocket handshake?

    101 means the connection is switching to another protocol. Sec-WebSocket-Accept, derived from the client's key, proves that the server understands WebSockets.
  2. 2. How is the Sec-WebSocket-Accept value computed?

    The server appends the specification's GUID to Sec-WebSocket-Key, hashes it with SHA-1 and base64-encodes the digest. It is a handshake check, not a secret.
  3. 3. Why does the frame decoder return leftover bytes?

    TCP is a byte stream without message boundaries. The decoder consumes complete frames and keeps the rest until more data arrives.
  4. 4. Which statement about masking is correct?

    The mask is a XOR with a random key, required for client-to-server frames to protect proxies from misinterpretation. It offers no confidentiality; use wss:// for that.
  5. 5. A client reports close code 1006. What does it mean?

    1006 is only reported locally when the connection dropped or the handshake failed, without a close frame. 1000 would be normal and 1009 message too big.

Summary

  • A WebSocket starts as an HTTP GET with Upgrade: websocket; the server answers 101 and a Sec-WebSocket-Accept computed as base64(SHA-1(key + GUID)).
  • After that, both sides exchange frames: opcode (text, binary, ping, pong, close), length (7, 16 or 64 bits), optional mask, payload. Client frames are masked, server frames are not.
  • TCP delivers a byte stream, so a parser must buffer partial frames.
  • Node 22+ provides a global WebSocket client with open, message, error and close events; servers are built on the 'upgrade' event of http.Server.
  • End connections with the closing handshake (1000 normal, 1009 too big, 1006 abnormal), use ping/pong for liveness, and reconnect with backoff.
  • Check Origin, authenticate during the handshake, use wss://, and limit message size and rate.
  • In production use ws (or Socket.IO when you need its extras), and a shared channel for multiple servers.

Next: UDP, DNS and Other Protocols