Switching Protocols
Production Risk
Low. This is the standard mechanism for protocol upgrades and is fundamental for technologies like WebSockets to function correctly.
This code is sent in response to an 'Upgrade' request header from the client, and indicates the protocol the server is switching to. The server will switch protocols to the one specified in the 'Upgrade' header.
- 1The client requests to switch from HTTP to a different protocol, such as WebSocket.
- 2The server supports the requested protocol switch and agrees to it.
- 3This is commonly used to initiate a WebSocket connection for real-time, bidirectional communication.
A web browser initiates a WebSocket connection to a server to enable a live chat feature.
GET /chat HTTP/1.1 Host: example.com Upgrade: websocket Connection: Upgrade
expected output
HTTP/1.1 101 Switching Protocols
Fix
Handle the protocol switch on the client side
// Browser WebSocket — the 101 upgrade is handled automatically
const socket = new WebSocket('wss://example.com/chat');
socket.addEventListener('open', () => {
console.log('Protocol switched to WebSocket (101 received)');
socket.send(JSON.stringify({ type: 'hello' }));
});
socket.addEventListener('message', (event) => {
const msg = JSON.parse(event.data);
console.log('Received:', msg);
});Why this works
After the server sends '101 Switching Protocols', the TCP connection is no longer HTTP — both sides must speak the negotiated protocol (e.g., WebSocket). The browser's WebSocket API and most HTTP client libraries handle the handshake automatically. The 'open' event fires once the 101 exchange completes and the connection is ready for full-duplex messaging.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev