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

HTTP Tunneling through Proxies

Handle the CONNECT method to facilitate secure tunneling through enterprise web proxies.

In this lesson, you will learn how to use the HTTP CONNECT method to establish a secure, opaque tunnel through an intermediary proxy server.

The Problem: Proxies vs. TLS

When you connect to a secure website (https://), your traffic is encrypted end-to-end. If your network requires a proxy, that proxy shouldn't be able to "see" or manipulate your HTTPS traffic. However, a standard proxy expects to see HTTP headers. The CONNECT method solves this by asking the proxy to open a raw TCP pipe between your Node.js application and the destination server. Once the proxy confirms the connection, it effectively gets out of the way, allowing your application to perform its own TLS handshake directly with the target.

How It Works in Node.js

When you send a CONNECT request, the proxy doesn't expect a standard GET or POST. Instead, it receives a request string formatted as CONNECT host:port HTTP/1.1.

If the proxy responds with 200 Connection Established, it means the tunnel is open. At this point, your Node.js client should stop treating the connection as an HTTP request and start treating the underlying socket as a raw duplex stream.

const net = require('net');

// 1. Connect to the proxy server
const proxySocket = net.connect(proxyPort, proxyHost);

// 2. Send the CONNECT request
proxySocket.write(`CONNECT target.com:443 HTTP/1.1\r\nHost: target.com\r\n\r\n`);

// 3. Listen for the confirmation
proxySocket.once('data', (data) => {
  if (data.toString().includes('200 Connection Established')) {
    // 4. Tunnel established! 
    // Now perform the TLS handshake over this socket
    const secureSocket = tls.connect({ socket: proxySocket, servername: 'target.com' });
    secureSocket.write('GET / HTTP/1.1\r\nHost: target.com\r\n\r\n');
  }
});

By switching from an HTTP request model to a raw TCP pipe, you ensure the proxy remains a "dumb" pipe, preserving the integrity of your TLS session. This is the foundation of how tools like HTTPSProxyAgent function in production environments.

Key Takeaway: The CONNECT method transforms a proxy from an HTTP intermediary into a raw TCP relay, allowing you to establish end-to-end encryption through restrictive network barriers.