Course contentsShow
← Node.js
Lesson 545 of 1,9806. Networking and HTTP FundamentalsFree lesson

Connection Upgrading for WebSockets

Handle the HTTP Upgrade header to transition a connection from plain HTTP to a full-duplex protocol.

In this lesson, you will learn how to transition a persistent HTTP connection into a full-duplex WebSocket tunnel by intercepting the HTTP Upgrade header.

Moving Beyond Request-Response

Normally, HTTP follows a rigid request-response pattern: the client asks, the server answers, and the interaction completes. However, some applications, like real-time chat or live dashboards, require the server to push data to the client without waiting for a request. This is where the Upgrade mechanism comes in.

The Handshake

When a client wants to switch protocols, it sends an HTTP request with specific headers:

  • Connection: Upgrade: Tells the server the client wants to change protocols.
  • Upgrade: websocket: Specifies the target protocol.
  • Sec-WebSocket-Key: A random string used to verify the handshake.

In Node.js, you handle this by listening for the upgrade event on the http.Server instance. Instead of handling a standard http.IncomingMessage, you intercept the raw underlying TCP socket before the HTTP lifecycle finishes.

Example: The Upgrade Interceptor

Here is how you capture that transition:

const http = require('http');

const server = http.createServer();

server.on('upgrade', (req, socket, head) => {
  // 1. Verify the 'Upgrade' header
  if (req.headers['upgrade'] !== 'websocket') {
    socket.end('HTTP/1.1 400 Bad Request');
    return;
  }

  // 2. Acknowledge the switch
  const resHeaders = [
    'HTTP/1.1 101 Switching Protocols',
    'Upgrade: websocket',
    'Connection: Upgrade',
    '\r\n'
  ].join('\r\n');

  socket.write(resHeaders);

  // 3. The socket is now a persistent, full-duplex pipe
  socket.on('data', (data) => {
    console.log('Received frame:', data);
  });
});

server.listen(8080);

The Shift in Responsibility

Once you send the 101 Switching Protocols status code, the HTTP server stops treating the stream as an HTTP exchange. You have successfully "hijacked" the socket. The connection remains open, and both the client and server can now write data to this stream independently, effectively bypassing the request-response constraints of HTTP. You are now responsible for managing the state, framing, and closure of this new persistent connection manually.

Key Takeaway: The HTTP Upgrade mechanism uses a standard request-response handshake to "hand off" control of the TCP socket, allowing the server to bypass HTTP semantics for real-time, bidirectional communication.