Node.js HTTP Proxy Middleware

3.0.5 · active · verified Wed Apr 22

http-proxy-middleware is a robust and flexible Node.js library designed to easily set up reverse proxies within various HTTP server frameworks such as Express, Connect, Next.js, Fastify, and Polka. It leverages http-proxy under the hood, providing a 'one-liner' API to proxy requests, handle WebSockets, rewrite paths, and modify requests/responses. The current stable major version is 3.x (specifically v3.0.5 as of recent updates), with v4.0.0 actively under development in beta, introducing some breaking changes and refinements. The library is known for its ease of integration and comprehensive configuration options, making it a popular choice for development environments and API gateway setups where requests need to be routed to different backend services. Patch releases are frequent, addressing bugs and minor improvements.

Common errors

Warnings

Install

Imports

Quickstart

Sets up an Express server that proxies requests starting with `/api` to 'jsonplaceholder.typicode.com', demonstrating path rewriting, WebSocket support, and custom event handlers.

import express from 'express';
import { createProxyMiddleware, Options } from 'http-proxy-middleware';

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

// Configuration for the proxy middleware
const apiProxyOptions: Options = {
  target: 'http://jsonplaceholder.typicode.com', // target host
  changeOrigin: true, // needed for virtual hosted sites
  ws: true, // proxy websockets
  pathRewrite: {
    '^/api': '', // rewrite path: remove `/api` prefix when forwarding to target
  },
  onProxyReq: (proxyReq, req, res) => {
    // Optional: Log proxy request details or modify headers
    console.log(`[Proxy] Proxying request: ${req.method} ${req.url} -> ${proxyReq.path}`);
  },
  onProxyRes: (proxyRes, req, res) => {
    // Optional: Log proxy response details or modify response headers
    console.log(`[Proxy] Received response for: ${req.url} with status: ${proxyRes.statusCode}`);
  },
  onError: (err, req, res, target) => {
    console.error(`[Proxy Error] ${err.message}`);
    res.status(500).send('Proxy Error');
  }
};

// Apply the proxy middleware to '/api' route
app.use('/api', createProxyMiddleware(apiProxyOptions));

// Basic route for the main application
app.get('/', (req, res) => {
  res.send('Hello from the main application!');
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
  console.log(`Try accessing http://localhost:${port}/api/todos/1`);
});

// To run this:
// 1. npm init -y
// 2. npm install express http-proxy-middleware @types/express @types/http-proxy-middleware typescript ts-node
// 3. Add "start": "ts-node app.ts" to package.json scripts
// 4. npm start

view raw JSON →