http-proxy

repository·master·Indexed 11 days ago

https://github.com/http-party/node-http-proxy

A highly configurable HTTP(S) proxy server for Node.js, version 1.18.1. It allows developers to intercept and forward incoming requests to target servers for load balancing, routing, and middleware integration. Supports WebSocket proxying, SSL/TLS configurations, and custom header modification via the proxyReq event.

Tokens
6K
Snippets
24
Records
29
Agent score
95%

What's inside http-proxy

  1. Replace deprecated Middleware and ProxyTable APIs

    master

    The Middleware API and ProxyTable API from version 0.x.x have been removed in version 1.x.x to increase core flexibility.

    • Middleware: You can implement custom logic that behaves like the old Middleware API using the new flexible API structure.
    • ProxyTable: To simulate the old ProxyTable API, use an add-on module like http-proxy-rules.
  2. Proxy HTTP and WebSocket traffic

    master

    In version 1.x.x, proxying is split into two distinct methods based on the protocol:

    1. HTTP/HTTPS: Use the .web(req, res) method on a proxy instance.
    2. WebSockets: Use the .ws(req, socket, head) method. This typically requires listening to the upgrade event on your HTTP server to intercept WebSocket requests.
    var proxy = new httpProxy.createProxyServer({
      target: {
        host: 'localhost',
        port: 9015
      }
    });
    
    var proxyServer = http.createServer(function (req, res) {
      proxy.web(req, res);
    });
    
    // Listen to the `upgrade` event and proxy the WebSocket requests
    proxyServer.on('upgrade', function (req, socket, head) {
      proxy.ws(req, socket, head);
    });
  3. Core Concepts of node-http-proxy

    master

    A proxy is created using createProxyServer(options). This returns a proxy object that provides four primary methods:

    • web(req, res, [options]): Used for proxying regular HTTP(S) requests.
    • ws(req, socket, head, [options]): Used for proxying WebSocket(S) requests.
    • listen(port): A convenience function that wraps the proxy object in a webserver and starts listening on the specified port.
    • close([callback]): Closes the inner webserver and stops listening.

    Important: Unless listen() is invoked, calling createProxyServer does not create a webserver; it only creates the proxy instance. You can then manually proxy requests by calling .web() inside your own http.createServer callback.

    var httpProxy = require('http-proxy');
    
    // Create the proxy instance
    var proxy = httpProxy.createProxyServer(options);
    
    // Manually proxying within a custom server
    http.createServer(function(req, res) {
      proxy.web(req, res, { target: 'http://mytarget.com:8080' });
    }).listen(8000);
  4. Run the Simple HTTP benchmark

    master

    To perform the Simple HTTP benchmark, you must have three separate terminal sessions running simultaneously: one for the proxy server, one for the target server, and one for the wrk load testing process.

    # 1. Start the proxy server
    node benchmark/scripts/proxy.js
    
    # 2. Start the target server
    node benchmark/scripts/hello.js
    
    # 3. Run the wrk process
    wrk -c 20 -d5m -t 2 http://127.0.0.1:8000
  5. Modify proxy request headers using 'proxyReq'

    master

    You can modify the outgoing request to the target server by listening for the proxyReq event. This is useful for adding custom headers (like authentication or tracking IDs) before the connection is established.

    var http = require('http'),
        httpProxy = require('http-proxy');
    
    var proxy = httpProxy.createProxyServer({});
    
    // Listen for 'proxyReq' to modify the request before it is sent to the target
    proxy.on('proxyReq', function(proxyReq, req, res, options) {
      proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
    });
    
    var server = http.createServer(function(req, res) {
      proxy.web(req, res, { target: 'http://127.0.0.1:5050' });
    });
    
    server.listen(5050);
  6. Configure HTTPS proxying

    master

    The library supports various HTTPS configurations:

    HTTPS -> HTTP

    Set the ssl option with key and cert to provide the proxy's certificate.

    HTTPS -> HTTPS

    Set target to an https:// URL and use secure: true to enable SSL certificate validation (prevents self-signed certs).

    HTTP -> HTTPS (using PKCS12)

    Provide a pfx file and passphrase in the target object.

    // HTTPS -> HTTPS example
    httpProxy.createServer({
      ssl: {
        key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
        cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
      },
      target: 'https://localhost:9010',
      secure: true
    }).listen(443);
  7. Proxy WebSockets

    master

    To support WebSockets, you must set ws: true in the proxy options. You also need to listen for the 'upgrade' event on your HTTP server and manually call proxy.ws(req, socket, head) to pipe the WebSocket connection.

    var http = require('http'),
        httpProxy = require('http-proxy');
    
    var proxy = new httpProxy.createProxyServer({
      target: {
        host: 'localhost',
        port: 9015
      },
      ws: true
    });
    
    var proxyServer = http.createServer(function (req, res) {
      proxy.web(req, res);
    });
    
    // Handle WebSocket upgrades
    proxyServer.on('upgrade', function (req, socket, head) {
      proxy.ws(req, socket, head);
    });
    
    proxyServer.listen(8015);
  8. Migrate from http-proxy 0.x.x to 1.x.x

    master

    Upgrading from http-proxy@0.x.x to http-proxy@1.0 (and later 1.x.x versions) involves breaking changes because the 1.0+ versions are a from-scratch implementation. Key changes include new methods for server creation, proxying (web vs websocket), and the removal of the built-in Middleware and ProxyTable APIs in favor of external modules or custom implementations.

    // Example of the new server creation pattern in 1.x.x
    httpProxy.createServer({
      target:'http://localhost:9003'
    }).listen(8003);
  9. Setup a basic stand-alone proxy server

    master

    To create a simple proxy that listens on a specific port and forwards all traffic to a target, use createProxyServer with a target option and call .listen().

    var http = require('http'),
        httpProxy = require('http-proxy');
    
    // Create your proxy server and set the target in the options.
    // Invoking listen(..) triggers the creation of a web server.
    httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000);
    
    // Create your target server for testing
    http.createServer(function (req, res) {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
      res.end();
    }).listen(9000);
  10. Handle errors in http-proxy 1.x.x

    master

    You can handle errors in two ways:

    1. Globally: Listen for the error event on the proxy instance. The callback receives (err, req, res).
    2. Locally: Pass a callback as the last parameter to the .web() or .ws() methods.
    var proxy = httpProxy.createServer({
      target:'http://localhost:9005'
    });
    
    proxy.listen(8005);
    
    // Listen for the `error` event on `proxy`
    proxy.on('error', function (err, req, res) {
      res.writeHead(500, {
        'Content-Type': 'text/plain'
      });
      
      res.end('Something went wrong. And we are reporting a custom error message.');
    });