Express HTTP Proxy Middleware Fork

1.1.0 · maintenance · verified Wed Apr 22

express-http-proxy-2 is an HTTP proxy middleware for the Express.js framework, designed to forward incoming requests to a specified target host and stream the responses back. This package is a community-maintained fork of the original `express-http-proxy` library, specifically created to address critical bugs, such as issue #509, and to provide comprehensive TypeScript type definitions, making it more robust for modern JavaScript and TypeScript projects. Currently at version 1.1.0, its release cadence is tied to bug fixes and feature enhancements derived from the community's needs, rather than a fixed schedule. Key differentiators include built-in support for streaming requests and responses, the ability to use Promises for asynchronous hooks, and flexible host selection which can be a static string or a dynamic function evaluated per request. It seamlessly integrates into Express applications, offering various configuration options to customize request path resolution, header manipulation, and conditional proxying.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting up `express-http-proxy-2` to proxy requests from `/api` to an external JSON API, including path rewriting and response modification.

import express from 'express';
import proxy from 'express-http-proxy-2';

const app = express();
const PORT = 3000;

// Configure the proxy middleware for requests to '/api'
// These requests will be forwarded to 'https://jsonplaceholder.typicode.com'
// and rewritten to remove '/api' from the path.
app.use('/api', proxy('https://jsonplaceholder.typicode.com', {
  proxyReqPathResolver: (req) => {
    // Example: change /api/users to /users
    const originalPath = req.url;
    const updatedPath = originalPath.replace('/api', '');
    console.log(`Proxying request: ${originalPath} -> ${updatedPath}`);
    return updatedPath;
  },
  userResDecorator: (proxyRes, proxyResData) => {
    // Optional: modify the response data from the proxied server
    console.log('Received response from proxy target.');
    const data = JSON.parse(proxyResData.toString('utf8'));
    // Add a custom header to the response indicating it was proxied
    proxyRes.headers['x-proxied-by'] = 'express-http-proxy-2';
    return JSON.stringify({ ...data, proxied: true });
  }
}));

// A simple health check route for the Express server itself
app.get('/health', (req, res) => {
  res.send('Server is healthy!');
});

app.listen(PORT, () => {
  console.log(`Express server listening on http://localhost:${PORT}`);
  console.log('Test proxy: curl http://localhost:3000/api/todos/1');
  console.log('Test local: curl http://localhost:3000/health');
});

view raw JSON →