Gathering detailed insights and metrics for http-proxy-middleware
Gathering detailed insights and metrics for http-proxy-middleware
Gathering detailed insights and metrics for http-proxy-middleware
Gathering detailed insights and metrics for http-proxy-middleware
@types/http-proxy-middleware
TypeScript definitions for http-proxy-middleware
express-http-proxy
http proxy middleware for express
proxy-middleware
http(s) proxy as connect middleware
@nuxtjs/proxy
> The one-liner node.js http-proxy middleware solution for Nuxt.js using [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware)
⚡ The one-liner node.js http-proxy middleware for connect, express, next.js and more
npm install http-proxy-middleware
Typescript
Module System
Min. Node Version
Node Version
NPM Version
83.3
Supply Chain
100
Quality
81.3
Maintenance
100
Vulnerability
100
License
Total
3,360,181,858
Last Day
606,260
Last Week
15,571,398
Last Month
66,219,583
Last Year
698,019,062
10,807 Stars
468 Commits
852 Forks
119 Watching
11 Branches
37 Contributors
Updated on 07 Dec 2024
Minified
Minified + Gzipped
TypeScript (98.82%)
JavaScript (1.18%)
Cumulative downloads
Total Downloads
Last day
-4%
606,260
Compared to previous day
Last week
4.2%
15,571,398
Compared to previous week
Last month
-0.1%
66,219,583
Compared to previous month
Last year
-0.2%
698,019,062
Compared to previous year
31
Node.js proxying made simple. Configure proxy middleware with ease for connect, express, next.js and many more.
Powered by the popular Nodejitsu http-proxy
.
This page is showing documentation for version v3.x.x (release notes)
See MIGRATION.md for details on how to migrate from v2.x.x to v3.x.x
If you're looking for older documentation. Go to:
Proxy /api
requests to http://www.example.org
:bulb: Tip: Set the option changeOrigin
to true
for name-based virtual hosted sites.
1// typescript 2 3import * as express from 'express'; 4import type { Request, Response, NextFunction } from 'express'; 5 6import { createProxyMiddleware } from 'http-proxy-middleware'; 7import type { Filter, Options, RequestHandler } from 'http-proxy-middleware'; 8 9const app = express(); 10 11const proxyMiddleware = createProxyMiddleware<Request, Response>({ 12 target: 'http://www.example.org/api', 13 changeOrigin: true, 14 }), 15 16app.use('/api', proxyMiddleware); 17 18app.listen(3000); 19 20// proxy and keep the same base path "/api" 21// http://127.0.0.1:3000/api/foo/bar -> http://www.example.org/api/foo/bar 22
All http-proxy
options can be used, along with some extra http-proxy-middleware
options.
http-proxy
eventshttp-proxy
options1npm install --save-dev http-proxy-middleware
Create and configure a proxy middleware with: createProxyMiddleware(config)
.
1const { createProxyMiddleware } = require('http-proxy-middleware'); 2 3const apiProxy = createProxyMiddleware({ 4 target: 'http://www.example.org', 5 changeOrigin: true, 6}); 7 8// 'apiProxy' is now ready to be used as middleware in a server.
options.target: target host to proxy to. (protocol + host)
options.changeOrigin: for virtual hosted sites
see full list of http-proxy-middleware
configuration options
An example with express
server.
1// include dependencies 2const express = require('express'); 3const { createProxyMiddleware } = require('http-proxy-middleware'); 4 5const app = express(); 6 7// create the proxy 8/** @type {import('http-proxy-middleware/dist/types').RequestHandler<express.Request, express.Response>} */ 9const exampleProxy = createProxyMiddleware({ 10 target: 'http://www.example.org/api', // target host with the same base path 11 changeOrigin: true, // needed for virtual hosted sites 12}); 13 14// mount `exampleProxy` in web server 15app.use('/api', exampleProxy); 16app.listen(3000);
If you want to use the server's app.use
path
parameter to match requests.
Use pathFilter
option to further include/exclude requests which you want to proxy.
1app.use( 2 createProxyMiddleware({ 3 target: 'http://www.example.org/api', 4 changeOrigin: true, 5 pathFilter: '/api/proxy-only-this-path', 6 }), 7);
app.use
documentation:
http-proxy-middleware options:
pathFilter
(string, []string, glob, []glob, function)Narrow down which requests should be proxied. The path
used for filtering is the request.url
pathname. In Express, this is the path
relative to the mount-point of the proxy.
path matching
createProxyMiddleware({...})
- matches any path, all requests will be proxied when pathFilter
is not configured.createProxyMiddleware({ pathFilter: '/api', ...})
- matches paths starting with /api
multiple path matching
createProxyMiddleware({ pathFilter: ['/api', '/ajax', '/someotherpath'], ...})
wildcard path matching
For fine-grained control you can use wildcard matching. Glob pattern matching is done by micromatch. Visit micromatch or glob for more globbing examples.
createProxyMiddleware({ pathFilter: '**', ...})
matches any path, all requests will be proxied.createProxyMiddleware({ pathFilter: '**/*.html', ...})
matches any path which ends with .html
createProxyMiddleware({ pathFilter: '/*.html', ...})
matches paths directly under path-absolutecreateProxyMiddleware({ pathFilter: '/api/**/*.html', ...})
matches requests ending with .html
in the path of /api
createProxyMiddleware({ pathFilter: ['/api/**', '/ajax/**'], ...})
combine multiple patternscreateProxyMiddleware({ pathFilter: ['/api/**', '!**/bad.json'], ...})
exclusionNote: In multiple path matching, you cannot use string paths and wildcard paths together.
custom matching
For full control you can provide a custom function to determine which requests should be proxied or not.
1/** 2 * @return {Boolean} 3 */ 4const pathFilter = function (path, req) { 5 return path.match('^/api') && req.method === 'GET'; 6}; 7 8const apiProxy = createProxyMiddleware({ 9 target: 'http://www.example.org', 10 pathFilter: pathFilter, 11});
pathRewrite
(object/function)Rewrite target's url path. Object-keys will be used as RegExp to match paths.
1// rewrite path 2pathRewrite: {'^/old/api' : '/new/api'} 3 4// remove path 5pathRewrite: {'^/remove/api' : ''} 6 7// add base path 8pathRewrite: {'^/' : '/basepath/'} 9 10// custom rewriting 11pathRewrite: function (path, req) { return path.replace('/api', '/base/api') } 12 13// custom rewriting, returning Promise 14pathRewrite: async function (path, req) { 15 const should_add_something = await httpRequestToDecideSomething(path); 16 if (should_add_something) path += "something"; 17 return path; 18}
router
(object/function)Re-target option.target
for specific requests.
1// Use `host` and/or `path` to match requests. First match will be used. 2// The order of the configuration matters. 3router: { 4 'integration.localhost:3000' : 'http://127.0.0.1:8001', // host only 5 'staging.localhost:3000' : 'http://127.0.0.1:8002', // host only 6 'localhost:3000/api' : 'http://127.0.0.1:8003', // host + path 7 '/rest' : 'http://127.0.0.1:8004' // path only 8} 9 10// Custom router function (string target) 11router: function(req) { 12 return 'http://127.0.0.1:8004'; 13} 14 15// Custom router function (target object) 16router: function(req) { 17 return { 18 protocol: 'https:', // The : is required 19 host: '127.0.0.1', 20 port: 8004 21 }; 22} 23 24// Asynchronous router function which returns promise 25router: async function(req) { 26 const url = await doSomeIO(); 27 return url; 28}
plugins
(Array)1const simpleRequestLogger = (proxyServer, options) => { 2 proxyServer.on('proxyReq', (proxyReq, req, res) => { 3 console.log(`[HPM] [${req.method}] ${req.url}`); // outputs: [HPM] GET /users 4 }); 5}, 6 7const config = { 8 target: `http://example.org`, 9 changeOrigin: true, 10 plugins: [simpleRequestLogger], 11};
ejectPlugins
(boolean) default: false
If you're not satisfied with the pre-configured plugins, you can eject them by configuring ejectPlugins: true
.
NOTE: register your own error handlers to prevent server from crashing.
1// eject default plugins and manually add them back
2
3const {
4 debugProxyErrorsPlugin, // subscribe to proxy errors to prevent server from crashing
5 loggerPlugin, // log proxy events to a logger (ie. console)
6 errorResponsePlugin, // return 5xx response on proxy error
7 proxyEventsPlugin, // implements the "on:" option
8} = require('http-proxy-middleware');
9
10createProxyMiddleware({
11 target: `http://example.org`,
12 changeOrigin: true,
13 ejectPlugins: true,
14 plugins: [debugProxyErrorsPlugin, loggerPlugin, errorResponsePlugin, proxyEventsPlugin],
15});
logger
(Object)Configure a logger to output information from http-proxy-middleware: ie. console
, winston
, pino
, bunyan
, log4js
, etc...
Only info
, warn
, error
are used internally for compatibility across different loggers.
If you use winston
, make sure to enable interpolation: https://github.com/winstonjs/winston#string-interpolation
See also logger recipes (recipes/logger.md) for more details.
1createProxyMiddleware({ 2 logger: console, 3});
http-proxy
eventsSubscribe to http-proxy events with the on
option:
1createProxyMiddleware({
2 target: 'http://www.example.org',
3 on: {
4 proxyReq: (proxyReq, req, res) => {
5 /* handle proxyReq */
6 },
7 proxyRes: (proxyRes, req, res) => {
8 /* handle proxyRes */
9 },
10 error: (err, req, res) => {
11 /* handle error */
12 },
13 },
14});
option.on.error: function, subscribe to http-proxy's error
event for custom error handling.
1function onError(err, req, res, target) { 2 res.writeHead(500, { 3 'Content-Type': 'text/plain', 4 }); 5 res.end('Something went wrong. And we are reporting a custom error message.'); 6}
option.on.proxyRes: function, subscribe to http-proxy's proxyRes
event.
1function onProxyRes(proxyRes, req, res) { 2 proxyRes.headers['x-added'] = 'foobar'; // add new header to response 3 delete proxyRes.headers['x-removed']; // remove header from response 4}
option.on.proxyReq: function, subscribe to http-proxy's proxyReq
event.
1function onProxyReq(proxyReq, req, res) { 2 // add custom header to request 3 proxyReq.setHeader('x-added', 'foobar'); 4 // or log the req 5}
option.on.proxyReqWs: function, subscribe to http-proxy's proxyReqWs
event.
1function onProxyReqWs(proxyReq, req, socket, options, head) { 2 // add custom header 3 proxyReq.setHeader('X-Special-Proxy-Header', 'foobar'); 4}
option.on.open: function, subscribe to http-proxy's open
event.
1function onOpen(proxySocket) { 2 // listen for messages coming FROM the target here 3 proxySocket.on('data', hybridParseAndLogMessage); 4}
option.on.close: function, subscribe to http-proxy's close
event.
1function onClose(res, socket, head) { 2 // view disconnected websocket connections 3 console.log('Client disconnected'); 4}
http-proxy
optionsThe following options are provided by the underlying http-proxy library.
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.ssl: object to be passed to https.createServer()
option.ws: true/false: if you want to proxy websockets
option.xfwd: true/false, adds x-forward headers
option.secure: true/false, if you want to verify the SSL Certs
option.toProxy: true/false, passes the absolute URL as the path
(useful for proxying to proxies)
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 (note: you will have to append / manually if required).
option.localAddress : Local interface string to bind for outgoing connections
option.changeOrigin: true/false, Default: false - changes the origin of the host header to the target URL
option.preserveHeaderKeyCase: true/false, Default: false - specify whether you want to keep letter case of response header key
option.auth : Basic authentication i.e. 'user:password' to compute an Authorization header.
option.hostRewrite: rewrites the location hostname on (301/302/307/308) redirects.
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.
option.cookieDomainRewrite: rewrites domain of set-cookie
headers. Possible values:
false
(default): disable cookie rewriting
String: new domain, for example cookieDomainRewrite: "new.domain"
. To remove the domain, use cookieDomainRewrite: ""
.
Object: mapping of domains to new domains, use "*"
to match all domains.
For example keep one domain unchanged, rewrite one domain and remove other domains:
1cookieDomainRewrite: { 2 "unchanged.domain": "unchanged.domain", 3 "old.domain": "new.domain", 4 "*": "" 5}
option.cookiePathRewrite: rewrites path of set-cookie
headers. Possible values:
false
(default): disable cookie rewriting
String: new path, for example cookiePathRewrite: "/newPath/"
. To remove the path, use cookiePathRewrite: ""
. To set path to root use cookiePathRewrite: "/"
.
Object: mapping of paths to new paths, use "*"
to match all paths.
For example, to keep one path unchanged, rewrite one path and remove other paths:
1cookiePathRewrite: { 2 "/unchanged.path/": "/unchanged.path/", 3 "/old.path/": "/new.path/", 4 "*": "" 5}
option.headers: object, adds request headers. (Example: {host:'www.example.org'}
)
option.proxyTimeout: timeout (in millis) when proxy receives no response from target
option.timeout: timeout (in millis) for incoming requests
option.followRedirects: true/false, Default: false - specify whether you want to follow redirects
option.selfHandleResponse true/false, if set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes
event
option.buffer: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option:
1'use strict'; 2 3const streamify = require('stream-array'); 4const HttpProxy = require('http-proxy'); 5const proxy = new HttpProxy(); 6 7module.exports = (req, res, next) => { 8 proxy.web( 9 req, 10 res, 11 { 12 target: 'http://127.0.0.1:4003/', 13 buffer: streamify(req.rawBody), 14 }, 15 next, 16 ); 17};
1// verbose api 2createProxyMiddleware({ pathFilter: '/', target: 'http://echo.websocket.org', ws: true });
In the previous WebSocket examples, http-proxy-middleware relies on a initial http request in order to listen to the http upgrade
event. If you need to proxy WebSockets without the initial http request, you can subscribe to the server's http upgrade
event manually.
1const wsProxy = createProxyMiddleware({ target: 'ws://echo.websocket.org', changeOrigin: true }); 2 3const app = express(); 4app.use(wsProxy); 5 6const server = app.listen(3000); 7server.on('upgrade', wsProxy.upgrade); // <-- subscribe to http 'upgrade'
Intercept requests from downstream by defining onProxyReq
in createProxyMiddleware
.
Currently the only pre-provided request interceptor is fixRequestBody
, which is used to fix proxied POST requests when bodyParser
is applied before this middleware.
Example:
1const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware'); 2 3const proxy = createProxyMiddleware({ 4 /** 5 * Fix bodyParser 6 **/ 7 on: { 8 proxyReq: fixRequestBody, 9 }, 10});
Intercept responses from upstream with responseInterceptor
. (Make sure to set selfHandleResponse: true
)
Responses which are compressed with brotli
, gzip
and deflate
will be decompressed automatically. The response will be returned as buffer
(docs) which you can manipulate.
With buffer
, response manipulation is not limited to text responses (html/css/js, etc...); image manipulation will be possible too. (example)
NOTE: responseInterceptor
disables streaming of target's response.
Example:
1const { createProxyMiddleware, responseInterceptor } = require('http-proxy-middleware'); 2 3const proxy = createProxyMiddleware({ 4 /** 5 * IMPORTANT: avoid res.end being called automatically 6 **/ 7 selfHandleResponse: true, // res.end() will be called internally by responseInterceptor() 8 9 /** 10 * Intercept response and replace 'Hello' with 'Goodbye' 11 **/ 12 on: { 13 proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => { 14 const response = responseBuffer.toString('utf8'); // convert buffer to string 15 return response.replace('Hello', 'Goodbye'); // manipulate response and return the result 16 }), 17 }, 18});
Check out interception recipes for more examples.
Node.js 17+ no longer prefers IPv4 over IPv6 for DNS lookups.
E.g. It's not guaranteed that localhost
will be resolved to 127.0.0.1
– it might just as well be ::1
(or some other IP address).
If your target server only accepts IPv4 connections, trying to proxy to localhost
will fail if resolved to ::1
(IPv6).
Ways to solve it:
target: "http://localhost"
to target: "http://127.0.0.1"
(IPv4).node
: node index.js --dns-result-order=ipv4first
. (Not recommended.)Note: There’s a thing called Happy Eyeballs which means connecting to both IPv4 and IPv6 in parallel, which Node.js doesn’t have, but explains why for example
curl
can connect.
Configure the DEBUG
environment variable enable debug logging.
See debug
project for more options.
1DEBUG=http-proxy-middleware* node server.js 2 3$ http-proxy-middleware proxy created +0ms 4$ http-proxy-middleware proxying request to target: 'http://www.example.org' +359ms
View and play around with working examples.
View the recipes for common use cases.
http-proxy-middleware
is compatible with the following servers:
Sample implementations can be found in the server recipes.
Run the test suite:
1# install dependencies 2$ yarn 3 4# linting 5$ yarn lint 6$ yarn lint:fix 7 8# building (compile typescript to js) 9$ yarn build 10 11# unit tests 12$ yarn test 13 14# code coverage 15$ yarn cover 16 17# check spelling mistakes 18$ yarn spellcheck
The MIT License (MIT)
Copyright (c) 2015-2024 Steven Chim
Stable Version
2
7.5/10
Summary
Denial of service in http-proxy-middleware
Affected Versions
>= 3.0.0, < 3.0.3
Patched Versions
3.0.3
7.5/10
Summary
Denial of service in http-proxy-middleware
Affected Versions
< 2.0.7
Patched Versions
2.0.7
Reason
no dangerous workflow patterns detected
Reason
8 commit(s) and 4 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
packaging workflow detected
Details
Reason
0 existing vulnerabilities detected
Reason
Found 2/30 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-12-02
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More