How to build a Node.js proxy for HTTP GET?

Awesome, Toby! But there’s one thing missing—this works great for HTTP, but what about HTTPS? If you try to proxy https://www.google.com, it won’t work because http.request() doesn’t support secure connections.

Here’s how you can support both HTTP & HTTPS in your Node.js proxy server:

const http = require('http');
const https = require('https');

http.createServer((client_req, client_res) => {
    const target = client_req.url.startsWith('/https/') ? https : http;
    const url = client_req.url.replace('/https/', ''); // Adjust path for HTTPS

    const options = {
        hostname: 'www.google.com',
        port: target === https ? 443 : 80,
        path: url,
        method: client_req.method,
        headers: client_req.headers
    };

    const proxy = target.request(options, (res) => {
        client_res.writeHead(res.statusCode, res.headers);
        res.pipe(client_res);
    });

    client_req.pipe(proxy);
}).listen(8080, () => console.log("Proxy running on port 8080"));

What’s New?

:heavy_check_mark: Handles both HTTP & HTTPS requests.

:heavy_check_mark: Secure sites (Google, Facebook, etc.) work seamlessly.

:heavy_check_mark: Future-proofing – No need to worry about protocol mismatches.

With this, your Node.js proxy server can now handle secure requests without any issues! :earth_africa::rocket: