How to Negotiate WebSocket Subprotocols
Use the Sec-WebSocket-Protocol header to select a versioned subprotocol, reject unsupported clients, and evolve the message format safely.
On this page
Introduction
A WebSocket connection carries an ordered stream of messages, but the transport does not define what those messages mean. Two endpoints can connect successfully and still be speaking different formats, resulting in a connection that stays open while every message is misinterpreted. The subprotocol mechanism prevents this: during the handshake the client lists the application protocols it supports, the server picks one, and both sides then agree on the message format before the first message flows.
This tutorial implements subprotocol negotiation for a Node.js WebSocket server. It covers the handshake header, selecting exactly one protocol, rejecting clients that support none, using the subprotocol as a version boundary, and testing negotiation and mismatch. The examples reference a chat service, but the pattern applies to any message-based protocol.
How the handshake negotiates
The client includes Sec-WebSocket-Protocol in its upgrade request, a comma-separated list of identifiers such as chat.v2, chat.v1, in order of preference. The server chooses one that it supports and echoes exactly that single value in its upgrade response. The WebSocket API then exposes the agreed protocol to the client so application code can branch on it. If the server supports none of the offered protocols, it should reject the handshake with 400 rather than accept on a protocol the client did not ask for.
Two rules matter. First, the server must echo exactly one identifier from the client’s list; a server that invents a new name or echoes the whole list produces an invalid handshake that conformant clients reject. Second, the negotiation is metadata only: it does not change framing or opcodes. Its value is as an application-level contract, so both sides know how to interpret the payload.
import { WebSocketServer } from 'ws';
const SUPPORTED = ['chat.v2', 'chat.v1'];
const wss = new WebSocketServer({
server,
handleProtocols: (protocols) => {
for (const proto of protocols) { // Set, in client order
if (SUPPORTED.includes(proto)) return proto;
}
return false; // none acceptable -> reject handshake
},
});
wss.on('connection', (ws, req, protocol) => {
ws.send(JSON.stringify({ type: 'hello', protocol }));
});
Use the subprotocol as a version boundary
The subprotocol name is the natural place to version the wire format. When the message schema changes incompatibly, introduce a new identifier such as chat.v2, keep serving chat.v1 while old clients remain, and let each connection pick the version it understands. This mirrors API versioning but at the connection level, and it is cleaner than adding a version field to every message, because the version is fixed once per connection rather than re-parsed on each frame.
Keep the version handlers separate. A single handler that branches on the version for every message rots as versions accumulate. Route the connection to a version-specific module at accept time, sharing the underlying transport and any common framing. When a version reaches zero usage, remove its identifier from the supported list and stop negotiating it.
type Handler = (ws: unknown, msg: unknown) => void;
const handlers: Record<string, Handler> = {
'chat.v1': handleV1,
'chat.v2': handleV2,
};
function attach(ws: { on: Function; close: Function }, protocol: string) {
const handle = handlers[protocol];
if (!handle) { ws.close(1002, 'unsupported protocol'); return; }
ws.on('message', (raw: string) => handle(ws, JSON.parse(raw)));
}
Reject clearly when nothing matches
If the client offers only subprotocols the server does not support, the server should fail the handshake rather than accept silently. Accepting a connection on a protocol the client did not offer leaves the client believing it agreed to one thing while the server sends another. A clean rejection lets the client fall back or upgrade. Return an HTTP error on the upgrade response so the WebSocket API reports the failure to the client’s error handler.
Be deliberate about whether the subprotocol is required. If the endpoint has a single stable format, the subprotocol is optional and the client may omit it; the server then uses its default format. If the format can vary, require the subprotocol so client and server never guess. Document which identifiers are supported and what each means, because the name is the only contract.
Test negotiation and mismatch
Test that a client offering chat.v2, chat.v1 connects and the agreed protocol is chat.v2. Test that a client offering only an unsupported protocol fails the handshake. Test that a v1 client and a v2 client each send and receive correctly on the same server, proving both handlers work. Assert that the server never echoes a protocol the client did not offer, which is the invalid-handshake trap.
curl -i -N -H 'Connection: Upgrade' -H 'Upgrade: websocket' \
-H 'Sec-WebSocket-Version: 13' -H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
-H 'Sec-WebSocket-Protocol: chat.v2, chat.v1' http://localhost:3000/ws
# expect the response to echo exactly one: Sec-WebSocket-Protocol: chat.v2
Common pitfalls
Accepting a connection without an agreed subprotocol, echoing the whole list instead of one identifier, inventing a protocol the client did not offer, branching on the version inside one handler, and never retiring an old identifier are the recurring mistakes. Selecting exactly one supported value, routing to a version handler, and pruning unused identifiers address them, and the mismatch and dual-client tests confirm the handshake behaves.
A subtler trap is ordering. The client lists protocols in preference order, but a server that iterates its own supported list instead of the client’s order can select a lower-priority protocol than the client wanted. Iterate the client’s list and return the first value you support, so the client’s stated preference wins. Log the selected protocol with the connection, because a mismatch between what the client expected and what the server chose is invisible until messages fail to parse, and a log line turns that into an obvious cause.
Conclusion
A WebSocket subprotocol is an application-level contract negotiated in the handshake. Offer supported identifiers from the client, echo exactly one from the server, reject when nothing matches, and use the identifier as the version boundary for the message format. Self-check by asserting the agreed protocol and by confirming an unsupported offer fails while both supported versions work. With negotiation in place, a connection cannot succeed while both sides disagree about what the bytes mean.
Sources: RFC 6455: The WebSocket Protocol, MDN: Sec-WebSocket-Protocol, MDN: The WebSocket API.
FAQ
- What is a WebSocket subprotocol?
- It is a named application-level protocol carried over the WebSocket transport, such as graphql-ws or a versioned custom protocol. The handshake selects one so both sides agree on the message format before any message is sent.
- How do I evolve the message format?
- Treat the subprotocol name as a versioned contract, for example chat.v2. When the schema changes incompatibly, add a new identifier, keep serving the old one during migration, and remove it when clients have moved.
Report a problem with this articleOpens a pre-filled issue on GitHub.