Connect/Express HTTP Proxy Middleware
raw JSON →middleware-proxy is a connect-compliant HTTP middleware designed for transparently redirecting incoming requests, primarily useful in development environments where a frontend served by Node.js needs to proxy API calls to a separate backend server. It simplifies integrated project development by allowing developers to access static assets through a local Node server while redirecting RESTful API calls to an external backend. The current stable version is 2.0.5, with recent releases focusing on bug fixes like handling HTTPS and URL parsing edge cases. The package provides a flexible API that supports regular expressions for URL matching and offers an optional feature to strip URL prefixes before forwarding requests, making it suitable for managing API gateway differences between development and production setups.
Common errors
error Error: Cannot find module 'middleware-proxy' ↓
npm install middleware-proxy or yarn add middleware-proxy. error TypeError: proxy is not a function ↓
const proxy = require('middleware-proxy'); for CommonJS. If upgrading from <v2.0.1, ensure you are now using app.use(proxy(...)) directly without an outer function wrapper. error Requests are not being proxied as expected, or are resulting in 404s/incorrect data. ↓
/api/v1 for http://localhost:8080/api/v1). Verify the 'server' URL is accurate and accessible. Ensure 'path_to_strip' correctly removes the desired prefix without altering the base path incorrectly (e.g., stripping /api from /api/posts to become /posts). Warnings
breaking Major refactor in v2.0.1 changed the return signature of the main export. Prior to v2.0.1, 'middleware-proxy' returned a function that *created* the middleware. Since v2.0.1, it directly returns the middleware function itself. ↓
Install
npm install middleware-proxy yarn add middleware-proxy pnpm add middleware-proxy Imports
- proxy wrong
import proxy from 'middleware-proxy';correctconst proxy = require('middleware-proxy');
Quickstart
const express = require('express');
const app = express();
const http = require('http');
const proxy = require('middleware-proxy');
// Basic Express setup
app.set('port', process.env.PORT || 3000);
app.use(express.static(__dirname + '/app')); // Serve static files from './app'
// Proxy requests starting with '/service' to http://localhost:8080
app.use(proxy('/service', 'http://localhost:8080'));
http.createServer(app).listen(app.get('port'), function() {
console.log(`Express server listening on port ${app.get('port')}`);
});