HTTP Proxy 3

1.23.2 · active · verified Tue Apr 21

http-proxy-3 is an actively maintained, modern rewrite of the popular `http-proxy` library for Node.js, currently at version 1.23.2. It provides programmable HTTP/HTTPS and WebSocket proxying capabilities, suitable for building reverse proxies, load balancers, or API gateways. Key differentiators include a complete rewrite in TypeScript for enhanced type safety and maintainability, full HTTP/2 support via the `fetch` API, and comprehensive updates to all dependent packages to address security vulnerabilities. The library explicitly fixes known socket leaks and uncatchable WebSocket errors present in the unmaintained original `http-proxy`. It is used in production by major projects like Vite, CoCalc, and JupyterHub, ensuring a stable and reliable solution for integrating application logic with proxy server functionality.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic HTTP and WebSocket proxy that forwards requests from port 8000 to a target server running on port 9000, demonstrating core proxying functionality and error handling.

import * as http from 'node:http';
import { createProxyServer, type ProxyServerOptions } from 'http-proxy-3';

// Create a target HTTP server
const targetServer = http.createServer((req, res) => {
  console.log(`Target received: ${req.method} ${req.url}`);
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from the target server!');
});

targetServer.listen(9000, () => {
  console.log('Target server listening on http://localhost:9000');
});

// Create a basic HTTP proxy server
const proxyOptions: ProxyServerOptions = {
  target: 'http://localhost:9000',
  ws: true // Enable websocket proxying
};

const proxy = createProxyServer(proxyOptions);

// Handle proxy errors
proxy.on('error', (err, req, res) => {
  console.error('Proxy Error:', err);
  if (res && res.writeHead) {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Something went wrong with the proxy.');
  }
});

// Create a proxy listening server
const proxyServer = http.createServer((req, res) => {
  console.log(`Proxying request: ${req.method} ${req.url}`);
  proxy.web(req, res);
});

proxyServer.on('upgrade', (req, socket, head) => {
  console.log(`Proxying websocket upgrade: ${req.url}`);
  proxy.ws(req, socket, head);
});

proxyServer.listen(8000, () => {
  console.log('Proxy server listening on http://localhost:8000');
  console.log('Test with: curl http://localhost:8000');
  console.log('Test websockets with a client connecting to ws://localhost:8000');
});

view raw JSON →