What is http-proxy-middleware?
The http-proxy-middleware package is a Node.js package that provides an HTTP proxy as a middleware for use with Node.js applications, particularly in conjunction with frameworks like Express. It allows developers to easily set up proxy rules to forward requests to other servers, which is useful for tasks like API forwarding, logging, handling CORS, and more.
What are http-proxy-middleware's main functionalities?
Proxy requests
This feature allows you to proxy requests to another server. In this example, all requests to '/api' on the local server are forwarded to 'http://www.example.org'.
const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org' });
app.use('/api', apiProxy);
Path Rewriting
This feature allows you to rewrite the path of the request URL before it gets proxied. In this example, the path '/api' is removed before the request is forwarded to 'http://www.example.org'.
const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware('/api', {
target: 'http://www.example.org',
pathRewrite: { '^/api': '' }
});
app.use('/api', apiProxy);
Custom Routing Logic
This feature allows you to implement custom routing logic. In this example, only GET requests to paths starting with '/api' are proxied to 'http://www.example.org'.
const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware((pathname, req) => {
return pathname.match('^/api') && req.method === 'GET';
}, { target: 'http://www.example.org' });
app.use(apiProxy);
Handling WebSockets
This feature allows you to proxy WebSocket connections. In this example, WebSocket connections to '/socket' are proxied to 'ws://www.example.org'.
const { createProxyMiddleware } = require('http-proxy-middleware');
const wsProxy = createProxyMiddleware('/socket', {
target: 'ws://www.example.org',
ws: true
});
app.use('/socket', wsProxy);
Other packages similar to http-proxy-middleware
express-http-proxy
express-http-proxy is similar to http-proxy-middleware but is specifically designed for use with Express. It offers similar features for proxying HTTP requests but may have different configuration options and middleware setup.
node-http-proxy
node-http-proxy is a full-featured HTTP proxy library for Node.js, which http-proxy-middleware is built upon. It provides more low-level control over proxying but requires more setup compared to the convenience middleware layer provided by http-proxy-middleware.
redbird
Redbird is a reverse proxy library for Node.js with built-in support for clustering, HTTP2, LetsEncrypt, and more. It is more feature-rich and suitable for more complex proxying needs compared to http-proxy-middleware, which is simpler and more focused on middleware use cases.
http-proxy-middleware
The one-liner proxy middleware for connect, express and browser-sync
Install
$ npm install --save-dev http-proxy-middleware
Core concept
Configure the proxy middleware.
var proxyMiddleware = require('http-proxy-middleware');
var proxy = proxyMiddleware('/api', {target: 'http://www.example.org'});
- context: matches provided context against request-urls' path.
Matching requests will be proxied to the target host.
Example:
'/api'
or ['/api', '/ajax']
. (more about context matching) - options.target: target host to proxy to.
Check out available proxy options.
Example
A simple example with express server.
var express = require('express');
var proxyMiddleware = require('http-proxy-middleware');
var context = '/api';
var options = {
target: 'http://www.example.org',
changeOrigin: true
};
var proxy = proxyMiddleware(context, options);
var app = express();
app.use(proxy);
app.listen(3000);
See more examples.
Tip: For name-based virtual hosted sites, you'll need to use the option changeOrigin
and set it to true
.
Compatible servers:
http-proxy-middleware is compatible with the following servers:
Options
-
(DEPRECATED) option.proxyHost: Use option.changeOrigin = true
instead.
-
option.pathRewrite: object, rewrite target's url path. Object-keys will be used as RegExp to match paths.
{
"^/old/api" : "/new/api",
"^/remove/api" : ""
}
The following options are provided by the underlying http-proxy.
- option.target: url string to be parsed with the url module
- option.forward: url string to be parsed with the url module
- option.agent: object to be passed to http(s).request (see Node's https agent and http agent objects)
- option.secure: true/false, if you want to verify the SSL Certs
- option.xfwd: true/false, adds x-forward headers
- option.toProxy: passes the absolute URL as the
path
(useful for proxying to proxies) - option.hostRewrite: rewrites the location hostname on (301/302/307/308) redirects.
Undocumented options are provided by the underlying http-proxy.
- option.headers: object, adds request headers. (Example:
{host:'www.example.org'}
- option.changeOrigin: true/false, adds host to request header.
- option.prependPath: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path>
- option.ignorePath: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request>
- option.localAddress : Local interface string to bind for outgoing connections
- option.auth : Basic authentication i.e. 'user:password' to compute an Authorization header.
- option.autoRewrite: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false.
- option.protocolRewrite: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null.
Context matching
Request URL's path-absolute and query will be used for context matching .
- URL:
http://example.com:8042/over/there?name=ferret#nose
- context:
/over/there?name=ferret
http-proxy-middleware offers several ways to decide which requests should be proxied:
More Examples
To run and view the proxy examples, clone the http-proxy-middleware repo and install the dependencies:
$ git clone https://github.com/chimurai/http-proxy-middleware.git
$ cd http-proxy-middleware
$ npm install
Then run whichever example you want:
$ node examples/connect
Or just explore the proxy examples' sources:
Tests
To run the test suite, first install the dependencies, then run:
$ npm test
$ npm run cover
License:
The MIT License (MIT)
Copyright (c) 2015 Steven Chim
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.