Video in progress

What is the Sec-WebSocket-Protocol header for, and how does a Spring STOMP endpoint negotiate the subprotocol?

The client sends a list of subprotocols it supports in the handshake, and the server picks one and returns it in the response. A Spring STOMP endpoint knows v10.stomp, v11.stomp and v12.stomp and picks the best match for what the client asked for.

📖 Answer

WebSocket only carries frames; it doesn't know what language the content is in. The subprotocol is the agreement on that "language":

// stomp.js does this for you
const ws = new WebSocket('wss://example.uz/ws', ['v12.stomp', 'v11.stomp']);
console.log(ws.protocol); // after the connection opens: "v12.stomp"

The request carries Sec-WebSocket-Protocol: v12.stomp, v11.stomp, and the server returns one of them in the response. If the server returns a protocol that isn't in the list, the client must reject the connection (RFC 6455). There's one more trap in practice: if the client asked for a protocol but the server left the header out of the response entirely, Chrome drops the handshake as an error.

In Spring, @EnableWebSocketMessageBroker registers a StompSubProtocolHandler, and SubProtocolWebSocketHandler picks the versions it supports in the handshake itself; you write nothing. With a raw handler, though:

var handshake = new DefaultHandshakeHandler();
handshake.setSupportedProtocols("chat.v2", "chat.v1");
registry.addHandler(chatHandler, "/ws/chat").setHandshakeHandler(handshake);

The chosen protocol is visible through session.getAcceptedProtocol(), and you can pick the message format based on it.

There's also a habit of stuffing a token into this header (because the browser doesn't allow other headers). It works, but the server has to echo it back in the response and the token ends up in logs, so I don't recommend it.