Comprehensive Guide to HTTP Proxy for Node.js

Welcome to the Comprehensive Guide on HTTP Proxy

This guide will introduce you to http-proxy in Node.js and walk you through various useful APIs along with practical code snippets to help you get started.

Introduction to HTTP Proxy

HTTP Proxy is a powerful tool that allows you to forward HTTP requests from a client to a server. This is useful in various scenarios such as load balancing, logging, or even modifying the requests as they pass through.

Core APIs of HTTP Proxy

Creating a Basic Proxy

The following example demonstrates how to create a basic HTTP proxy server using the http-proxy module.

  const http = require('http');
  const httpProxy = require('http-proxy');
  
  // Create a new proxy server
  const proxy = httpProxy.createProxyServer();
  
  // Create a new HTTP server to listen for incoming requests
  const server = http.createServer((req, res) => {
    proxy.web(req, res, { target: 'http://localhost:9000' });
  });
  
  server.listen(8000, () => {
    console.log('Proxy server is running on http://localhost:8000');
  });

Handling Proxy Events

You can handle various events emitted by the proxy server, such as error, proxyReq, and proxyRes.

  const httpProxy = require('http-proxy');
  const proxy = httpProxy.createProxyServer();
  
  proxy.on('error', (err, req, res) => {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Something went wrong. And we are reporting a custom error message.');
  });
  
  proxy.on('proxyRes', (proxyRes, req, res) => {
    console.log('RAW Response from the target:', JSON.stringify(proxyRes.headers, true, 2));
  });
  
  proxy.listen(8000);

Modifying Request Headers

You can modify the headers of the requests before they are sent to the target server.

  const httpProxy = require('http-proxy');
  const proxy = httpProxy.createProxyServer();
  
  proxy.on('proxyReq', (proxyReq, req, res) => {
    // Add custom header to request
    proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
  });
  
  proxy.listen(8000);

Using HTTP Proxy with HTTPS

The following example demonstrates how to use http-proxy with HTTPS.

  const fs = require('fs');
  const https = require('https');
  const httpProxy = require('http-proxy');
  
  // Certificates for SSL
  const options = {
    key: fs.readFileSync('server.key', 'utf8'),
    cert: fs.readFileSync('server.cert', 'utf8')
  };

  // Create a proxy server
  const proxy = httpProxy.createProxyServer();
  
  // Create an HTTPS server to listen for incoming HTTPS requests
  const server = https.createServer(options, (req, res) => {
    proxy.web(req, res, { target: 'https://example.com' });
  });

  server.listen(443, () => {
    console.log('HTTPS proxy server is running on https://localhost');
  });

Creating an App Example with HTTP Proxy

Let’s create a simple application that uses http-proxy to forward requests from one server to another.

  // app.js
  const http = require('http');
  const httpProxy = require('http-proxy');
  
  const proxy = httpProxy.createProxyServer({ target: 'http://localhost:5000' });
  
  const server = http.createServer((req, res) => {
    // Log the request
    console.log(`Request made to: ${req.url}`);
    // Forward the request to the target server
    proxy.web(req, res);
  });
  
  server.listen(3000, () => {
    console.log('App server is running on http://localhost:3000');
  });
  
  // targetServer.js
  const http = require('http');
  
  const targetServer = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Response from the target server');
  });
  
  targetServer.listen(5000, () => {
    console.log('Target server is running on http://localhost:5000');
  });

Run node targetServer.js and node app.js to start the servers. You can test the proxy by visiting http://localhost:3000.

We hope this guide helps you leverage the power of http-proxy in your applications!

Hash: 9a95c8719e6c8f8afa781718ee0de67a325ba6c9ff4fd096d6b57d0e6e5a2a40

Leave a Reply

Your email address will not be published. Required fields are marked *