### Setup a basic stand-alone proxy server with a target Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md This example sets up a basic HTTP proxy server that forwards all incoming requests to a specified target server (`http://localhost:9000`). It also includes code for a simple target server that responds to proxied requests. ```javascript import * as http from "node:http"; import { createProxyServer } from "http-proxy-3"; // Create your proxy server and set the target in the options. createProxyServer({ target: "http://localhost:9000" }).listen(8000); // See (†) // Create your target server http .createServer((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); ``` -------------------------------- ### Setup a Basic Stand-alone Proxy Server Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Provides a practical example of setting up a simple, stand-alone proxy server that forwards requests to a target server. ```APIDOC ## Setup a Basic Stand-alone Proxy Server ### Description This example demonstrates how to configure and run a basic, stand-alone HTTP proxy server using `http-proxy-3`. It sets a target URL and listens on a specified port, forwarding incoming requests to the target. ### Method `createProxyServer(options).listen(port)` ### Parameters #### Request Body (for `createProxyServer`) - **options** (object) - Required - Configuration object. Must include a `target` property. - **target** (string) - The URL of the target server to proxy requests to. #### Path Parameters (for `listen`) - **port** (number) - Required - The port number on which the proxy server will listen for incoming connections. ### Request Example ```js import * as http from "node:http"; import { createProxyServer } from "http-proxy-3"; // Create and configure the proxy server const proxy = createProxyServer({ target: "http://localhost:9000" }); // Start listening on port 8000 proxy.listen(8000); // Example target server http .createServer((req, res) => { res.writeHead(200, { "Content-Type": "text/plain" }); res.write( "request successfully proxied!" ); res.end(); }) .listen(9000); ``` ### Response - **proxy server instance** - An object with methods to manage the proxy. - **listening on port** - The proxy server becomes active and starts accepting connections on the specified port. ### Response Example When a request is made to `http://localhost:8000`, it will be forwarded to `http://localhost:9000`. The response from the target server will be returned to the client. If the target server responds with text, that text will be received by the client. ``` -------------------------------- ### Setup Stand-alone Proxy Server with Custom Logic (Node.js) Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md This example demonstrates setting up a standalone HTTP proxy server using http-proxy-3. It allows for custom logic to be applied to incoming requests before they are proxied to the target server. The `proxy.web()` method is used for HTTP requests. ```javascript import * as http from "node:http"; import { createProxyServer } from "http-proxy-3"; // Create a proxy server with custom application logic const proxy = createProxyServer({}); // Create your custom server and just call `proxy.web()` to proxy // a web request to the target passed in the options // also you can use `proxy.ws()` to proxy a websockets request const server = http.createServer((req, res) => { // You can define here your custom logic to handle the request // and then proxy the request. proxy.web(req, res, { target: "http://127.0.0.1:5050" }); }); console.log("listening on port 5050"); server.listen(5050); ``` -------------------------------- ### Setup Stand-alone Proxy Server with Latency (Node.js) Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md This example demonstrates how to introduce latency into the proxying process. A custom HTTP server is created that simulates a delay using `setTimeout` before forwarding the request to the target server using `proxy.web()`. A separate target server is also set up to receive and respond to proxied requests. ```javascript import * as http from "node:http"; import { createProxyServer } from "http-proxy-3"; // Create a proxy server with latency const proxy = createProxyServer(); // Create your server that makes an operation that waits a while // and then proxies the request http .createServer((req, res) => { // This simulates an operation that takes 500ms to execute setTimeout(function () { proxy.web(req, res, { target: "http://localhost:9008", }); }, 500); }) .listen(8008); // Create your target server http .createServer(function (req, res) { res.writeHead(200, { "Content-Type": "text/plain" }); res.write( "request successfully proxied to: " + req.url + "\n" + JSON.stringify(req.headers, true, 2), ); res.end(); }) .listen(9008); ``` -------------------------------- ### Configure http-proxy-3 Server Options Source: https://context7.com/sagemathinc/http-proxy-3/llms.txt Demonstrates how to configure ServerOptions for the createProxyServer function in http-proxy-3. This includes setting the target server, enabling WebSocket proxying, handling headers, and configuring SSL. The example shows a comprehensive set of options for a typical proxy setup. ```typescript import { createProxyServer, ServerOptions } from "http-proxy-3"; const options: ServerOptions = { // Target server URL (required for proxying, can be set per-request) target: "http://localhost:9000", // Forward proxy URL (fire-and-forget, no response) forward: "http://logging-server:9001", // Custom HTTP agent agent: undefined, // SSL configuration for HTTPS proxy server ssl: { key: "...", cert: "..." }, // Enable WebSocket proxying ws: true, // Add X-Forwarded-* headers xfwd: true, // Verify target SSL certificate secure: true, // Pass absolute URL as path (for proxy-to-proxy) toProxy: false, // Prepend target path to request path prependPath: true, // Ignore incoming request path ignorePath: false, // Local interface for outgoing connections localAddress: undefined, // Change Host header to target URL changeOrigin: false, // Preserve header key case in response preserveHeaderKeyCase: false, // Basic auth for target (user:password) auth: undefined, // Rewrite redirect hostname hostRewrite: undefined, // Auto-rewrite redirects based on request autoRewrite: false, // Rewrite redirect protocol protocolRewrite: undefined, // Cookie domain rewriting rules cookieDomainRewrite: false, // Cookie path rewriting rules cookiePathRewrite: false, // Extra headers for target requests headers: {}, // Timeout for target response (ms) proxyTimeout: 120000, // Timeout for incoming requests (ms) timeout: undefined, // Follow redirects from target followRedirects: false, // Disable automatic response handling selfHandleResponse: false, // Request body stream buffer: undefined, // Override HTTP method method: undefined, // Custom CA certificates ca: undefined, // Enable fetch-based proxying (for HTTP/2) fetchOptions: { requestOptions: {}, onBeforeRequest: async (opts, req, res, options) => {}, onAfterResponse: async (response, req, res, options) => {} } }; const proxy = createProxyServer(options); ``` -------------------------------- ### Setup Stand-alone Proxy Server with Request Header Rewriting (Node.js) Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md This example shows how to configure a proxy server to modify outgoing request headers. It demonstrates two approaches: using the 'proxyReq' event for traditional HTTP/HTTPS servers and using the `onBeforeRequest` callback for fetch-based requests with HTTP/2 support. ```javascript import * as http from "node:http"; import { createProxyServer } from "http-proxy-3"; // Create a proxy server with custom application logic const proxy = createProxyServer({}); // To modify the proxy connection before data is sent, you can listen // for the 'proxyReq' event. When the event is fired, you will receive // the following arguments: // (http.ClientRequest proxyReq, http.IncomingMessage req, // http.ServerResponse res, Object options). This mechanism is useful when // you need to modify the proxy request before the proxy connection // is made to the target. proxy.on("proxyReq", (proxyReq, req, res, options, socket) => { proxyReq.setHeader("X-Special-Proxy-Header", "foobar"); }); const server = http.createServer((req, res) => { // You can define here your custom logic to handle the request // and then proxy the request. proxy.web(req, res, { target: "http://127.0.0.1:5050", }); }); console.log("listening on port 5050"); server.listen(5050); ``` ```javascript import * as http from "node:http"; import { createProxyServer } from "http-proxy-3"; import { Agent } from "undici"; // Create a proxy server with fetch and HTTP/2 support const proxy = createProxyServer({ target: "https://127.0.0.1:5050", fetchOptions: { requestOptions: {dispatcher: new Agent({ allowH2: true })} , // Modify the request before it's sent onBeforeRequest: async (requestOptions, req, res, options) => { requestOptions.headers['X-Special-Proxy-Header'] = 'foobar'; requestOptions.headers['X-HTTP2-Enabled'] = 'true'; }, // Access the response after it's received onAfterResponse: async (response, req, res, options) => { console.log(`Proxied ${req.url} -> ${response.status}`); } } }); const server = http.createServer((req, res) => { // The headers are modified via the onBeforeRequest callback proxy.web(req, res); }); console.log("listening on port 5050"); server.listen(5050); ``` -------------------------------- ### HTTP/2 Proxy Setup with Fetch API (Shorthand) Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md A simplified method to enable fetch for proxying, including HTTP/2 support if the runtime permits. This shorthand uses default fetch configurations, making it easier to integrate HTTP/2 proxying. It's an experimental feature. ```javascript // Shorthand to enable fetch with defaults const proxy = createProxyServer({ target: "https://http2-server.example.com", fetch // Uses default fetch configuration }); ``` -------------------------------- ### Install http-proxy-3 using npm Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md This command installs the http-proxy-3 package as a project dependency using npm. It is the first step to using the library in your Node.js project. ```bash npm install http-proxy-3 --save ``` -------------------------------- ### HTTP/2 Proxy Setup with Fetch API (Advanced Callbacks) Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Provides advanced configuration for HTTP/2 proxying using the Fetch API, including custom request options, callbacks for pre-request modification (`onBeforeRequest`) and post-response handling (`onAfterResponse`). This allows fine-grained control over the proxying process and is an experimental feature. ```javascript const proxy = createProxyServer({ target: "https://api.example.com", fetchOptions: { requestOptions: { // Use undici's Agent for HTTP/2 support dispatcher: new Agent({ allowH2: true, connect: { rejectUnauthorized: false, // For self-signed certs timeout: 10000 } }), // Additional fetch request options headersTimeout: 30000, bodyTimeout: 60000 }, // Called before making the fetch request onBeforeRequest: async (requestOptions, req, res, options) => { // Modify outgoing request requestOptions.headers['X-API-Key'] = 'your-api-key'; requestOptions.headers['X-Request-ID'] = Math.random().toString(36); }, // Called after receiving the fetch response onAfterResponse: async (response, req, res, options) => { // Access full response object console.log(`Status: ${response.status}`); console.log('Headers:', response.headers); // Note: response.body is a stream that will be piped to res automatically } } }); ``` -------------------------------- ### WebSocket Proxy Server Setup Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Demonstrates how to configure http-proxy-3 to proxy WebSocket connections. This is achieved by setting the `ws` option to `true` in the proxy server configuration. The example shows a proxy listening on port 8014 for WebSocket traffic. ```javascript // Create a proxy server for websockets httpProxy .createServer({ target: "ws://localhost:9014", ws: true, }) .listen(8014); ``` -------------------------------- ### HTTP/2 Proxy Setup with Fetch API (Global Dispatcher) Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Enables HTTP/2 support for all outgoing fetch requests by setting a global dispatcher with `allowH2: true`. This configuration is runtime-agnostic but relies on the underlying runtime's HTTP/2 capabilities. It's an experimental feature. ```javascript import { createProxyServer } from "http-proxy-3"; import { Agent, setGlobalDispatcher } from "undici"; // Either enable HTTP/2 for all fetch operations setGlobalDispatcher(new Agent({ allowH2: true })); // Or create a proxy with HTTP/2 support using fetch const proxy = createProxyServer({ target: "https://http2-server.example.com", fetchOptions: { requestOptions: {dispatcher: new Agent({ allowH2: true })} } }); ``` -------------------------------- ### Using HTTPS with http-proxy-3 (Node.js) Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md This example shows how to configure the proxy server to use HTTPS. It demonstrates creating an HTTPS proxy server that connects to an HTTP target. The `ssl` option is used to provide the necessary key and certificate files for the HTTPS server, and `secure: true` can be set to validate the target's SSL certificate. ```javascript // Create the HTTPS proxy server in front of a HTTP server httpProxy .createServer({ target: { host: "localhost", port: 9009, }, ssl: { key: fs.readFileSync("valid-ssl-key.pem", "utf8"), cert: fs.readFileSync("valid-ssl-cert.pem", "utf8"), }, }) .listen(8009); ``` -------------------------------- ### Run Tests for http-proxy-3 (Shell) Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md This command executes the test suite for the http-proxy-3 project using the pnpm package manager. It's a standard way to verify the functionality and integrity of the proxy implementation. Ensure pnpm is installed and the project dependencies are met before running. ```shell pnpm test ``` -------------------------------- ### HTTPS to HTTPS Proxy Server Setup Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Configures an http-proxy-3 server to forward incoming HTTPS requests to a specified HTTPS target. It requires SSL key and certificate files for the proxy server and the target URL. The `secure` option controls whether to validate the target's SSL certificate. ```javascript // Create the proxy server listening on port 443 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, // Depends on your needs, could be false. }) .listen(443); ``` -------------------------------- ### Buffer Option Example for httpProxy.createProxyServer Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Demonstrates how to use the 'buffer' option with httpProxy.createProxyServer to restream request body data. This is useful when middleware consumes the request stream before proxying. ```javascript 'use strict'; const streamify = require('stream-array'); const HttpProxy = require('http-proxy'); const proxy = new HttpProxy(); module.exports = (req, res, next) => { proxy.web(req, res, { target: 'http://localhost:4003/', buffer: streamify(req.rawBody) }, next); }; ``` -------------------------------- ### Round Robin Load Balancer with http-proxy-3 Source: https://context7.com/sagemathinc/http-proxy-3/llms.txt Implements a basic round-robin load balancer using http-proxy-3. It dynamically selects backend servers for each incoming request in a cyclical manner. This example requires the 'http-proxy-3' and 'node:http' modules. ```typescript import { createProxyServer } from "http-proxy-3"; import * as http from "node:http"; const backends = [ { host: "backend1", port: 3001 }, { host: "backend2", port: 3002 }, { host: "backend3", port: 3003 } ]; let currentIndex = 0; const proxy = createProxyServer({}); proxy.on("error", (err, req, res) => { console.error("Proxy error:", err); res.writeHead(502); res.end("Bad Gateway"); }); const server = http.createServer((req, res) => { const backend = backends[currentIndex]; const target = `http://${backend.host}:${backend.port}`; console.log(`Routing request to ${target}`); proxy.web(req, res, { target }); currentIndex = (currentIndex + 1) % backends.length; }); server.listen(8000, () => { console.log("Load balancer running on port 8000"); }); ``` -------------------------------- ### Forward Proxy Configuration with http-proxy-3 Source: https://context7.com/sagemathinc/http-proxy-3/llms.txt Demonstrates configuring http-proxy-3 as a forward proxy. This setup sends requests to another server without returning a response to the client, useful for logging or analytics. It also shows a combined scenario where requests are forwarded and proxied simultaneously. ```typescript import { createProxyServer } from "http-proxy-3"; // Forward-only proxy (no response to client) const forwardOnlyProxy = createProxyServer({ forward: "http://analytics-server:9000" }).listen(8000); // Combined forward and target proxy const combinedProxy = createProxyServer({ target: "http://main-backend:3000", forward: "http://logging-server:9001" }).listen(8001); // Requests are forwarded to logging-server AND proxied to main-backend // Client receives response from main-backend only ``` -------------------------------- ### Core Concept and Initialization Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Demonstrates how to create a proxy server instance using `createProxyServer` and the basic methods available: `web`, `ws`, `listen`, and `close`. ```APIDOC ## Core Concept and Initialization ### Description This section explains how to create a proxy server instance using the `createProxyServer` function and outlines the primary methods available on the returned proxy object: `web` for HTTP/S requests, `ws` for WebSocket requests, `listen` to wrap the proxy in a web server, and `close` to shut down the server. ### Method `createProxyServer(options)` ### Parameters #### Request Body - **options** (object) - Optional - Configuration options for the proxy server. See [lib/http-proxy/index.ts](lib/http-proxy/index.ts) for valid properties. ### Request Example ```js import { createProxyServer } from "http-proxy-3"; const options = { /* ... */ }; const proxy = createProxyServer(options); ``` ### Response An object with the following methods: - **web**: `req, res, [options]` - Proxies regular HTTP(S) requests. - **ws**: `req, socket, head, [options]` - Proxies WS(S) requests. - **listen**: `port` - Wraps the proxy object in a webserver. - **close**: `[callback]` - Closes the inner webserver. ### Response Example ```js import * as http from "node:http"; import { createProxyServer } from "http-proxy-3"; const proxy = createProxyServer(); http.createServer((req, res) => { proxy.web(req, res, { target: "http://mytarget.com:8080" }); }); proxy.on('error', (err) => { /* handle error */ }); ``` ``` -------------------------------- ### Create a basic proxy server instance Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Demonstrates how to create a proxy server instance using `createProxyServer` from the http-proxy-3 library. The `options` object configures the proxy's behavior, and the returned proxy object has methods for handling web and WebSocket requests, listening on a port, and closing the server. ```javascript import { createProxyServer } from "http-proxy-3"; const proxy = createProxyServer(options); // See below ``` -------------------------------- ### Create Proxy Server Instance with http-proxy-3 Source: https://context7.com/sagemathinc/http-proxy-3/llms.txt Demonstrates how to create a proxy server instance using `createProxyServer` from the http-proxy-3 library. This function is the main entry point and returns an object with methods for proxying requests, handling WebSockets, and managing the server lifecycle. It can be used with a custom HTTP server or in standalone mode. ```typescript import { createProxyServer } from "http-proxy-3"; import * as http from "node:http"; // Create a basic proxy server const proxy = createProxyServer({ target: "http://localhost:9000" }); // Use with a custom HTTP server const server = http.createServer((req, res) => { proxy.web(req, res); }); server.listen(8000); // Or use the built-in listen method for a standalone proxy const standaloneProxy = createProxyServer({ target: "http://localhost:9000" }).listen(8000); // Cleanup when done standaloneProxy.close(); ``` -------------------------------- ### Server Options Configuration Source: https://context7.com/sagemathinc/http-proxy-3/llms.txt This section details the various configuration options available for the `createProxyServer` function in http-proxy-3. These options allow for fine-grained control over how the proxy server handles incoming requests and forwards them to target servers. ```APIDOC ## Server Options Reference Complete configuration options for `createProxyServer`. All options are optional and can be overridden per-request. ### Description This object allows you to configure the behavior of the proxy server, including the target server, WebSocket support, SSL settings, request/response modifications, and more. ### Method `createProxyServer(options: ServerOptions)` ### Parameters #### Request Body (ServerOptions) - **target** (string) - Optional - The target server URL to which requests will be proxied. This is required for basic proxying and can be overridden on a per-request basis. - **forward** (string) - Optional - A URL for a forward proxy (fire-and-forget, no response is returned to the client). Useful for logging or analytics. - **agent** (http.Agent | https.Agent | undefined) - Optional - A custom HTTP or HTTPS agent to use for outgoing connections to the target server. - **ssl** (object) - Optional - SSL configuration for the HTTPS proxy server itself (not for the target). Contains `key` and `cert` properties. - **ws** (boolean) - Optional - Enable WebSocket proxying. Defaults to `false`. - **xfwd** (boolean) - Optional - If `true`, `X-Forwarded-*` headers (like `X-Forwarded-For`, `X-Forwarded-Proto`) will be added to the request sent to the target. - **secure** (boolean) - Optional - If `true`, the proxy will verify the SSL certificate of the target server when connecting via HTTPS. Defaults to `true`. - **toProxy** (boolean) - Optional - If `true`, the absolute URL will be passed as the path to the target. Useful for proxy-to-proxy scenarios. Defaults to `false`. - **prependPath** (boolean) - Optional - If `true`, the `target` path will be prepended to the request path. Defaults to `true`. - **ignorePath** (boolean) - Optional - If `true`, the incoming request path will be ignored, and only the `target` path will be used. Defaults to `false`. - **localAddress** (string | undefined) - Optional - The local interface to use for outgoing connections. - **changeOrigin** (boolean) - Optional - If `true`, the `Host` header of the incoming request will be changed to match the target server's hostname. Defaults to `false`. - **preserveHeaderKeyCase** (boolean) - Optional - If `true`, the case of header keys in the response will be preserved. Defaults to `false`. - **auth** (string | undefined) - Optional - Basic authentication credentials for the target server in the format `"username:password"`. - **hostRewrite** (string | undefined) - Optional - Rewrites the `Host` header of the outgoing request to the specified value. - **autoRewrite** (boolean) - Optional - Automatically rewrites redirects based on the original request. Defaults to `false`. - **protocolRewrite** (string | undefined) - Optional - Rewrites the protocol of redirects (e.g., `http` to `https`). - **cookieDomainRewrite** (string | boolean | undefined) - Optional - Rewrites the `Domain` attribute of `Set-Cookie` headers. Can be a string (new domain) or `true` (rewrite to target domain). - **cookiePathRewrite** (string | boolean | undefined) - Optional - Rewrites the `Path` attribute of `Set-Cookie` headers. Can be a string (new path) or `true` (rewrite to target path). - **headers** (object) - Optional - An object containing extra headers to be sent with requests to the target server. - **proxyTimeout** (number) - Optional - Timeout in milliseconds for receiving a response from the target server. Defaults to `120000` (2 minutes). - **timeout** (number | undefined) - Optional - Timeout in milliseconds for incoming requests. If not set, it defaults to the proxy timeout. - **followRedirects** (boolean) - Optional - If `true`, the proxy will automatically follow redirects from the target server. Defaults to `false`. - **selfHandleResponse** (boolean) - Optional - If `true`, the proxy will not automatically handle the response from the target. You must manually send the response using `res.end()` or similar. Defaults to `false`. - **buffer** (stream.Readable | undefined) - Optional - A stream that will be used as the request body for the target. - **method** (string | undefined) - Optional - Overrides the HTTP method of the incoming request for the proxied request. - **ca** (Buffer[] | string[] | undefined) - Optional - Custom CA certificates to trust when verifying the target server's SSL certificate. - **fetchOptions** (object) - Optional - Options for enabling fetch-based proxying, primarily for HTTP/2 support. Includes `requestOptions`, `onBeforeRequest`, and `onAfterResponse` callbacks. - **requestOptions** (object) - Optional - Additional options for the underlying `fetch` request. - **onBeforeRequest** (function) - Optional - A callback function executed before a request is sent to the target. - **onAfterResponse** (function) - Optional - A callback function executed after a response is received from the target. ### Request Example ```json { "target": "http://localhost:9000", "forward": "http://logging-server:9001", "ws": true, "xfwd": true, "secure": false, "headers": { "x-custom-header": "value" }, "proxyTimeout": 60000 } ``` ### Response #### Success Response (200) - **N/A** - The proxy server itself does not return a response body in the standard sense. It forwards the response from the target server to the client, or handles errors/forwarding as configured. #### Response Example *The response example depends entirely on the target server's response. The proxy forwards this directly.* ``` -------------------------------- ### HTTP/2 Support with Fetch API Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Demonstrates how to enable HTTP/2 support when using the fetch API for proxying. This feature is experimental. ```APIDOC ## POST /createProxyServer (HTTP/2 Fetch) ### Description Creates a proxy server that leverages the native fetch API to communicate with HTTP/2 servers. This feature is experimental and requires runtime-specific configuration for Node.js. ### Method POST ### Endpoint /createProxyServer ### Parameters #### Request Body - **target** (string) - Required - The target HTTPS URL to proxy requests to. - **fetchOptions** (object) - Optional - Advanced configuration for the fetch request. - **requestOptions** (object) - Optional - Options passed to the underlying fetch implementation. - **dispatcher** (object) - Optional - A dispatcher instance (e.g., `undici.Agent`) for controlling connection behavior, including HTTP/2 support (`allowH2: true`). - **connect** (object) - Optional - Connection-specific options for the dispatcher (e.g., `rejectUnauthorized`, `timeout`). - **headersTimeout** (number) - Optional - Timeout for headers in milliseconds. - **bodyTimeout** (number) - Optional - Timeout for the request body in milliseconds. - **onBeforeRequest** (function) - Optional - A callback function executed before the fetch request is made. Allows modification of request options. - **onAfterResponse** (function) - Optional - A callback function executed after the fetch response is received. Allows access to the response object. - **fetch** (boolean) - Optional - Shorthand to enable fetch with default configurations. ### Request Example (Basic HTTP/2 Setup) ```json { "target": "https://http2-server.example.com", "fetchOptions": { "requestOptions": { "dispatcher": "new Agent({ allowH2: true })" } } } ``` ### Request Example (Simple Fetch Enablement) ```json { "target": "https://http2-server.example.com", "fetch": true } ``` ### Request Example (Advanced Configuration) ```json { "target": "https://api.example.com", "fetchOptions": { "requestOptions": { "dispatcher": "new Agent({ allowH2: true, connect: { rejectUnauthorized: false, timeout: 10000 } })", "headersTimeout": 30000, "bodyTimeout": 60000 }, "onBeforeRequest": "async (requestOptions, req, res, options) => { ... }", "onAfterResponse": "async (response, req, res, options) => { ... }" } } ``` ### Response #### Success Response (200) Indicates the proxy server was successfully created with HTTP/2 fetch support enabled. #### Response Example ```json { "message": "HTTP/2 fetch proxy server created" } ``` ``` -------------------------------- ### Modify Proxy Response with http-proxy-3 (JavaScript) Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md This example demonstrates how to intercept and modify the response from a proxied server using http-proxy-3's `selfHandleResponse` option. It involves listening for the `proxyRes` event, reading the response body, and then sending a custom response back to the client. This requires careful handling to ensure the client receives a response. ```javascript const option = { target: target, selfHandleResponse: true, }; proxy.on("proxyRes", (proxyRes, req, res) => { var body = []; proxyRes.on("data", (chunk) => { body.push(chunk); }); proxyRes.on("end", () => { body = Buffer.concat(body).toString(); console.log("res from proxied server:", body); res.end("my response to cli"); }); }); proxy.web(req, res, option); ``` -------------------------------- ### Proxy a regular HTTP request Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Shows how to use the `proxy.web` method to forward an incoming HTTP request (`req`) and response (`res`) to a specified target server. This is a fundamental operation for setting up a proxy server. ```javascript http.createServer((req, res) => { proxy.web(req, res, { target: "http://mytarget.com:8080" }); }); ``` -------------------------------- ### HTTP Proxy Server Options Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Configuration options for creating and customizing an HTTP proxy server. ```APIDOC ## HTTP Proxy Server Options This section details the various options that can be passed to the `httpProxy.createProxyServer` method to customize its behavior. ### Options Overview - **target** (url string): The target URL to which requests will be proxied. This URL is parsed using Node.js's `url` module. - **forward** (url string | URL object): A forward proxy URL or object. If only a forward proxy is set without a target, requests are forwarded but the response is not returned to the caller. - **agent** (object): An object to be passed to `http.request` or `https.request`. This allows customization of the underlying HTTP/S agents. - **ssl** (object): An object to be passed to `https.createServer()`. Used for configuring SSL/TLS settings for the proxy server itself. - **ws** (boolean): If `true`, the proxy will handle WebSocket connections. - **xfwd** (boolean): If `true`, adds `X-Forwarded-*` headers to the proxied requests. - **secure** (boolean): If `true`, verifies the SSL certificates of the target server. Set to `false` to proxy to servers with self-signed certificates. - **toProxy** (boolean): If `true`, the absolute URL of the incoming request is passed as the `path` option. Useful for proxying to other proxy servers. - **prependPath** (boolean): Default: `true`. If `true`, the target's path is prepended to the proxy path. - **ignorePath** (boolean): Default: `false`. If `true`, the path of the incoming request is ignored. Manual path appending might be required. - **localAddress** (string): The local interface string to bind for outgoing connections. - **changeOrigin** (boolean): Default: `false`. If `true`, changes the `Host` header of the outgoing request to match the target URL's origin. - **preserveHeaderKeyCase** (boolean): Default: `false`. If `true`, preserves the original casing of response header keys. - **auth** (string): Basic authentication credentials in the format 'user:password'. This will be used to compute an `Authorization` header. - **hostRewrite** (string): Rewrites the `Location` hostname on redirects (301, 302, 307, 308). - **autoRewrite** (boolean): Default: `false`. Rewrites the `Location` host/port on redirects based on the requested host/port. - **protocolRewrite** (string): Rewrites the `Location` protocol on redirects to 'http' or 'https'. Default: `null`. - **cookieDomainRewrite** (string | object | boolean): Rewrites the domain of `Set-Cookie` headers. - `false` (default): Disables cookie domain rewriting. - String: The new domain to use (e.g., `"new.domain"`). Use `""` to remove the domain. - Object: A mapping of domains to new domains. `"*"` matches all domains. Example: ```json { "unchanged.domain": "unchanged.domain", "old.domain": "new.domain", "*": "" } ``` - **cookiePathRewrite** (string | object | boolean): Rewrites the path of `Set-Cookie` headers. - `false` (default): Disables cookie path rewriting. - String: The new path to use (e.g., `"/newPath/"`). Use `""` to remove the path. Use `"/"` to set the path to root. - Object: A mapping of paths to new paths. `"*"` matches all paths. Example: ```json { "/unchanged.path/": "/unchanged.path/", "/old.path/": "/new.path/", "*": "" } ``` - **headers** (object): An object containing extra headers to be added to the proxied requests. - **proxyTimeout** (number): Timeout in milliseconds for outgoing proxy requests. - **timeout** (number): Timeout in milliseconds for incoming requests. - **followRedirects** (boolean): Default: `false`. If `true`, the proxy will follow redirects. - **selfHandleResponse** (boolean): If `true`, the proxy will not automatically handle responses. You are responsible for listening to the `proxyRes` event and returning the response. - **buffer** (stream): A stream of data to be sent as the request body. Useful when middleware consumes the request stream before proxying. Example: ```javascript 'use strict'; const streamify = require('stream-array'); const HttpProxy = require('http-proxy'); const proxy = new HttpProxy(); module.exports = (req, res, next) => { proxy.web(req, res, { target: 'http://localhost:4003/', buffer: streamify(req.rawBody) }, next); }; ``` - **ca** (Buffer | string | Array): Optionally override the trusted CA certificates. This is passed to `https.request`. - **fetchOptions** (object): Enables the Fetch API for HTTP/2 support. Provide an object of type `FetchOptions` for custom configuration: - `requestOptions`: Additional fetch request options (e.g., undici Agent with `allowH2: true` for HTTP/2 as dispatcher). - `onBeforeRequest`: Async callback called before making the fetch request. - `onAfterResponse`: Async callback called after receiving the fetch response. ### Notes - `options.ws` and `options.ssl` are optional. ``` -------------------------------- ### Listen for Proxy Events with http-proxy-3 (JavaScript) Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md This code snippet demonstrates how to create a proxy server using http-proxy-3 and listen for common events such as 'error', 'proxyRes', and 'open'. It shows how to handle errors, log response headers, and process messages from the target WebSocket. ```javascript import { createProxyServer } from "http-proxy-3"; const proxy = createProxyServer({ target: "http://localhost:9005", }); proxy.listen(8005); // Listen for the `error` event on `proxy`. 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."); }); // Listen for the `proxyRes` event on `proxy`. proxy.on("proxyRes", (proxyRes, req, res) => { console.log( "RAW Response from the target", JSON.stringify(proxyRes.headers, true, 2), ); }); // Listen for the `open` event on `proxy`. proxy.on("open", (proxySocket) => { // listen for messages coming FROM the target here proxySocket.on("data", hybiParseAndLogMessage); }); ``` -------------------------------- ### HTTP to HTTPS Proxy with Client Certificate Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md Sets up an HTTP proxy server that forwards requests to an HTTPS target, utilizing a PKCS12 client certificate for authentication. This is useful when the target server requires client certificate validation. The proxy listens on port 8000. ```javascript // Create an HTTP proxy server with an HTTPS target httpProxy .createProxyServer({ target: { protocol: "https:", host: "my-domain-name", port: 443, pfx: fs.readFileSync("path/to/certificate.p12"), passphrase: "password", }, changeOrigin: true, }) .listen(8000); ``` -------------------------------- ### createProxyServer Source: https://context7.com/sagemathinc/http-proxy-3/llms.txt Creates a new proxy server instance. This is the main entry point for configuring and managing proxy behavior. ```APIDOC ## createProxyServer ### Description Creates a new proxy server instance with the specified options. This is the main entry point for the library. The returned object provides methods for proxying HTTP requests (`web`), WebSocket connections (`ws`), starting a standalone server (`listen`), and shutting down (`close`). ### Method `createProxyServer(options)` ### Parameters #### Options Object - **target** (string | URL | object) - The target server URL or configuration. - **ws** (boolean) - Enable WebSocket proxying. Defaults to `false`. - **ssl** (object) - SSL configuration for HTTPS proxying. Contains `key`, `cert`, `pfx`, `passphrase`. - **secure** (boolean) - Controls SSL certificate verification for the target. Defaults to `true`. - **changeOrigin** (boolean) - Changes the origin of the host header to the target's host. Defaults to `false`. ### Request Example ```typescript import { createProxyServer } from "http-proxy-3"; import * as http from "node:http"; // Create a basic proxy server const proxy = createProxyServer({ target: "http://localhost:9000" }); // Use with a custom HTTP server const server = http.createServer((req, res) => { proxy.web(req, res); }); server.listen(8000); // Or use the built-in listen method for a standalone proxy const standaloneProxy = createProxyServer({ target: "http://localhost:9000" }).listen(8000); // Cleanup when done standaloneProxy.close(); ``` ### Response Returns a proxy server instance with methods like `web`, `ws`, `listen`, and `close`. ``` -------------------------------- ### Configure Callback Functions for Fetch/HTTP2 in http-proxy-3 (JavaScript) Source: https://github.com/sagemathinc/http-proxy-3/blob/main/README.md This snippet demonstrates how to configure callback functions, `onBeforeRequest` and `onAfterResponse`, within http-proxy-3 when using the fetch/HTTP2 path. It shows how to modify request headers before sending and inspect the response status and headers after receiving. Dependencies include 'http-proxy-3' and 'undici'. ```javascript import { createProxyServer } from "http-proxy-3"; import { Agent } from "undici"; const proxy = createProxyServer({ target: "https://api.example.com", fetchOptions: { requestOptions: {dispatcher: new Agent({ allowH2: true })}, // Called before making the fetch request onBeforeRequest: async (requestOptions, req, res, options) => { // Modify the outgoing request requestOptions.headers['X-Custom-Header'] = 'added-by-callback'; console.log('Making request to:', requestOptions.headers.host); }, // Called after receiving the fetch response onAfterResponse: async (response, req, res, options) => { // Access the full response object console.log(`Response: ${response.status}`, response.headers); // Note: response.body is a stream that will be piped to res automatically } } }); // Listen for the `close` event on `proxy`. proxy.on("close", (res, socket, head) => { // view disconnected websocket connections console.log("Client disconnected"); }); ``` -------------------------------- ### Enable HTTP/2 with Fetch and undici Agent Source: https://context7.com/sagemathinc/http-proxy-3/llms.txt Enables HTTP/2 support by configuring the fetch options with an undici Agent. This directs the proxy to use the fetch-based code path instead of native Node.js HTTP modules. Requires 'undici' and 'http-proxy-3' packages. ```typescript import { createProxyServer } from "http-proxy-3"; import { Agent } from "undici"; import { readFileSync } from "node:fs"; const http2Agent = new Agent({ allowH2: true, connect: { rejectUnauthorized: false } }); const proxy = createProxyServer({ target: "https://http2-server:8443", ssl: { key: readFileSync("server-key.pem", "utf8"), cert: readFileSync("server-cert.pem", "utf8") }, fetchOptions: { requestOptions: { dispatcher: http2Agent } } }).listen(8443); ``` -------------------------------- ### Cookie and Header Rewriting with http-proxy-3 Source: https://context7.com/sagemathinc/http-proxy-3/llms.txt Demonstrates how to rewrite cookie domains, paths, and add custom headers using http-proxy-3. It also includes options for `autoRewrite`, `hostRewrite`, and `protocolRewrite` for managing redirects and host information. ```typescript import { createProxyServer } from "http-proxy-3"; const proxy = createProxyServer({ target: "http://backend.internal:9000", changeOrigin: true, // Rewrite cookie domains cookieDomainRewrite: { "backend.internal": "frontend.example.com", "*": "" // Remove domain from all other cookies }, // Rewrite cookie paths cookiePathRewrite: { "/api/v1/": "/", "*": "/" }, // Add custom headers to proxied requests headers: { "X-Proxy-Server": "http-proxy-3", "X-Real-Host": "frontend.example.com" }, // Rewrite redirect locations autoRewrite: true, hostRewrite: "frontend.example.com", protocolRewrite: "https" }).listen(8000); ``` -------------------------------- ### Configure HTTPS Proxying with http-proxy-3 Source: https://context7.com/sagemathinc/http-proxy-3/llms.txt Demonstrates how to configure HTTPS proxying by providing SSL certificates. This includes setting up HTTPS-to-HTTPS and HTTP-to-HTTPS proxy targets. The `secure` option can be set to `false` to disable SSL certificate verification, which is useful for self-signed certificates. Client certificates can also be configured for secure connections. ```typescript import { createProxyServer } from "http-proxy-3"; import { readFileSync } from "node:fs"; // HTTPS proxy to HTTPS target const proxy = createProxyServer({ target: "https://secure-backend:9443", ssl: { key: readFileSync("server-key.pem", "utf8"), cert: readFileSync("server-cert.pem", "utf8") }, // Set to false for self-signed certificates secure: false }).listen(8443); // HTTP proxy to HTTPS target with client certificate const httpToHttpsProxy = createProxyServer({ target: { protocol: "https:", host: "secure-api.example.com", port: 443, pfx: readFileSync("client-certificate.p12"), passphrase: "certificate-password" }, changeOrigin: true }).listen(8000); ```