How to create a simple http proxy in node.js?

Learn how to create a simple http proxy in node.js? with practical examples, diagrams, and best practices. Covers javascript, node.js, proxy development techniques with visual explanations.

Build a Basic HTTP Proxy Server with Node.js

Hero image for How to create a simple http proxy in node.js?

Learn how to create a simple HTTP proxy server using Node.js, enabling you to forward requests and responses between clients and target servers.

An HTTP proxy server acts as an intermediary for requests from clients seeking resources from other servers. It can be used for various purposes, such as logging, caching, security, or simply forwarding requests. This article will guide you through building a basic HTTP proxy server in Node.js, demonstrating how to handle incoming client requests and forward them to a target server.

Understanding the Proxy Mechanism

At its core, an HTTP proxy server receives an HTTP request from a client, processes it (or not), and then sends a new HTTP request to the intended target server. Once the target server responds, the proxy receives that response and forwards it back to the original client. This process involves handling HTTP headers, request bodies, and ensuring a seamless flow of data.

sequenceDiagram
    participant Client
    participant ProxyServer as Node.js Proxy
    participant TargetServer

    Client->>ProxyServer: HTTP Request (e.g., GET /data)
    activate ProxyServer
    ProxyServer->>TargetServer: Forwarded HTTP Request
    activate TargetServer
    TargetServer-->>ProxyServer: HTTP Response
    deactivate TargetServer
    ProxyServer-->>Client: Forwarded HTTP Response
    deactivate ProxyServer

Sequence diagram illustrating the request/response flow through a Node.js proxy server.

Setting Up Your Node.js Proxy

To create our proxy, we'll use Node.js's built-in http module. The process involves creating an HTTP server that listens for incoming requests. When a request arrives, we'll parse its details (method, URL, headers, body) and then make a new request to the target server. Finally, we'll pipe the target server's response back to the client.

const http = require('http');

const PORT = 8080;
const TARGET_HOST = 'jsonplaceholder.typicode.com'; // Example target API
const TARGET_PORT = 80;

const proxy = http.createServer((req, res) => {
  console.log(`Proxying request: ${req.method} ${req.url}`);

  const options = {
    hostname: TARGET_HOST,
    port: TARGET_PORT,
    path: req.url,
    method: req.method,
    headers: {
      ...req.headers,
      host: TARGET_HOST // Important: set host header to target host
    }
  };

  const proxyReq = http.request(options, (proxyRes) => {
    console.log(`Target responded with status: ${proxyRes.statusCode}`);
    // Set proxy response headers to client response
    for (const header in proxyRes.headers) {
      res.setHeader(header, proxyRes.headers[header]);
    }
    res.writeHead(proxyRes.statusCode);
    proxyRes.pipe(res, { end: true }); // Pipe target response to client
  });

  proxyReq.on('error', (err) => {
    console.error('Proxy request error:', err);
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Proxy Error: Could not reach target server.');
  });

  req.pipe(proxyReq, { end: true }); // Pipe client request body to proxy request
});

proxy.listen(PORT, () => {
  console.log(`Proxy server listening on port ${PORT}`);
  console.log(`Forwarding requests to ${TARGET_HOST}:${TARGET_PORT}`);
});

Basic Node.js HTTP proxy server implementation.

Running and Testing Your Proxy

To test your proxy, you'll need to start the Node.js script and then configure your client (e.g., a web browser, curl, or a custom application) to use your proxy server. For curl, you can specify the proxy using the -x flag.

1. Save the code

Save the provided JavaScript code as proxy.js in a new directory.

2. Install dependencies (if any)

For this basic example, no external npm packages are required, as we're using Node.js's built-in http module.

3. Start the proxy server

Open your terminal or command prompt, navigate to the directory where you saved proxy.js, and run node proxy.js. You should see output indicating the proxy server is listening.

4. Test with curl

Open another terminal and execute a curl command, specifying your proxy. For example, to fetch data from jsonplaceholder.typicode.com/posts/1 through your proxy, you would use: curl -x http://localhost:8080 http://jsonplaceholder.typicode.com/posts/1.

5. Observe output

You should see the JSON response from jsonplaceholder.typicode.com in your curl terminal, and your proxy server's console will log the request and response status.