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
Middleware for connect and browser-sync
Install
npm install --save-dev http-proxy-middleware
Usage
core concept
Create and configure the proxy middleware so it can be used as middleware in connect or browser-sync.
var proxyMiddleware = require('http-proxy-middleware');
var proxy = proxyMiddleware(context, options);
context
path to proxy. Example: '/api'options.target
target host to proxy to. (See "Options" for all options)
connect
Example: Proxy http://localhost:3000/ajax requests to http://cdnjs.cloudfare.com/ajax
var http = require('http');
var connect = require('connect');
var proxyMiddleware = require('http-proxy-middleware');
var context = '/ajax';
var proxy = proxyMiddleware(context, {target: 'http://cdnjs.cloudflare.com'});
var app = connect();
app.use(context, proxy);
http.createServer(app).listen(3000);
browser-sync
Example: Proxy http://localhost:3000/ajax requests to http://cdnjs.cloudfare.com/ajax
var browserSync = require('browser-sync');
var proxyMiddleware = require('http-proxy-middleware');
var proxy = proxyMiddleware('/ajax', {target: 'http://cdnjs.cloudflare.com'});
browserSync({
server: {
baseDir: "./",
port: 3000,
middleware: [proxy]
}
});
gulp + browser-sync
Example: Proxy http://localhost:3000/ajax requests to http://cdnjs.cloudfare.com/ajax
var gulp = require('gulp');
var browserSync = require('browser-sync');
var proxyMiddleware = require('http-proxy-middleware');
gulp.task('serve', function () {
var proxy = proxyMiddleware('/ajax', {target: 'http://cdnjs.cloudflare.com'});
browserSync({
server: {
baseDir: "./",
port: 3000,
middleware: [proxy]
}
});
});
gulp.task('default', ['serve']);
Options
http-proxy options:
These options are provided by the underlying http-proxy.
- target: url string to be parsed with the url module
- forward: url string to be parsed with the url module
- agent: object to be passed to http(s).request (see Node's https agent and http agent objects)
- secure: true/false, if you want to verify the SSL Certs
- xfwd: true/false, adds x-forward headers
- toProxy: passes the absolute URL as the
path
(useful for proxying to proxies) - hostRewrite: rewrites the location hostname on (301/302/307/308) redirects.
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.