{"id":13457848,"url":"https://github.com/chimurai/http-proxy-middleware","last_synced_at":"2025-05-12T16:16:28.976Z","repository":{"id":28698813,"uuid":"32219142","full_name":"chimurai/http-proxy-middleware","owner":"chimurai","description":":zap: The one-liner node.js http-proxy middleware for connect, express, next.js and more","archived":false,"fork":false,"pushed_at":"2025-04-21T20:51:16.000Z","size":3519,"stargazers_count":10962,"open_issues_count":112,"forks_count":870,"subscribers_count":117,"default_branch":"master","last_synced_at":"2025-05-05T14:13:13.132Z","etag":null,"topics":["browser-sync","connect","express","fastify","http-proxy","javascript","middleware","nextjs","node","nodejs","polka","proxy","proxy-middleware","websocket"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chimurai.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2015-03-14T15:45:55.000Z","updated_at":"2025-05-05T03:50:13.000Z","dependencies_parsed_at":"2024-01-29T07:26:28.290Z","dependency_job_id":"e012536a-e7a3-412b-8b41-8d0dc756008c","html_url":"https://github.com/chimurai/http-proxy-middleware","commit_stats":{"total_commits":439,"total_committers":40,"mean_commits":10.975,"dds":0.4829157175398633,"last_synced_commit":"77f320e4dca8247167471393dcbce2b1e333b7cf"},"previous_names":[],"tags_count":74,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chimurai%2Fhttp-proxy-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chimurai%2Fhttp-proxy-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chimurai%2Fhttp-proxy-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chimurai%2Fhttp-proxy-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chimurai","download_url":"https://codeload.github.com/chimurai/http-proxy-middleware/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253726733,"owners_count":21954094,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["browser-sync","connect","express","fastify","http-proxy","javascript","middleware","nextjs","node","nodejs","polka","proxy","proxy-middleware","websocket"],"created_at":"2024-07-31T09:00:38.289Z","updated_at":"2025-05-12T16:16:28.954Z","avatar_url":"https://github.com/chimurai.png","language":"TypeScript","funding_links":[],"categories":["Proxying API Requests in Development","TypeScript","Repository","语言资源库","网络服务","express","websocket","nodejs","1. 后端开发",":hammer_and_wrench: 开发","⚙️ Backend \u0026 APIs"],"sub_categories":["Configuring the Proxy Manually","HTTP","typescript","网络服务_其他","1.1 HTTP","dev server 代理"],"readme":"# http-proxy-middleware\n\n[![GitHub Workflow Status (with branch)](https://img.shields.io/github/actions/workflow/status/chimurai/http-proxy-middleware/ci.yml?branch=master\u0026logo=github-actions\u0026logoColor=white\u0026style=flat-square)](https://github.com/chimurai/http-proxy-middleware/actions/workflows/ci.yml?query=branch%3Amaster)\n[![Coveralls](https://img.shields.io/coveralls/chimurai/http-proxy-middleware.svg?style=flat-square\u0026logo=coveralls)](https://coveralls.io/r/chimurai/http-proxy-middleware)\n[![Known Vulnerabilities](https://snyk.io/test/github/chimurai/http-proxy-middleware/badge.svg)](https://snyk.io/test/github/chimurai/http-proxy-middleware)\n[![npm](https://img.shields.io/npm/v/http-proxy-middleware?color=%23CC3534\u0026style=flat-square\u0026logo=npm)](https://www.npmjs.com/package/http-proxy-middleware)\n\nNode.js proxying made simple. Configure proxy middleware with ease for [connect](https://github.com/senchalabs/connect), [express](https://github.com/expressjs/express), [next.js](https://github.com/vercel/next.js) and [many more](#compatible-servers).\n\nPowered by the popular Nodejitsu [`http-proxy`](https://github.com/http-party/node-http-proxy). [![GitHub stars](https://img.shields.io/github/stars/http-party/node-http-proxy.svg?style=social\u0026label=Star)](https://github.com/http-party/node-http-proxy)\n\n## ⚠️ Note \u003c!-- omit in toc --\u003e\n\nThis page is showing documentation for version v3.x.x ([release notes](https://github.com/chimurai/http-proxy-middleware/releases))\n\nSee [MIGRATION.md](https://github.com/chimurai/http-proxy-middleware/blob/master/MIGRATION.md) for details on how to migrate from v2.x.x to v3.x.x\n\nIf you're looking for older documentation. Go to:\n\n- \u003chttps://github.com/chimurai/http-proxy-middleware/tree/v2.0.4#readme\u003e\n- \u003chttps://github.com/chimurai/http-proxy-middleware/tree/v0.21.0#readme\u003e\n\n## TL;DR \u003c!-- omit in toc --\u003e\n\nProxy `/api` requests to `http://www.example.org`\n\n:bulb: **Tip:** Set the option `changeOrigin` to `true` for [name-based virtual hosted sites](http://en.wikipedia.org/wiki/Virtual_hosting#Name-based).\n\n```typescript\n// typescript\nimport * as express from 'express';\nimport type { NextFunction, Request, Response } from 'express';\nimport { createProxyMiddleware } from 'http-proxy-middleware';\nimport type { Filter, Options, RequestHandler } from 'http-proxy-middleware';\n\nconst app = express();\n\nconst proxyMiddleware = createProxyMiddleware\u003cRequest, Response\u003e({\n  target: 'http://www.example.org/api',\n  changeOrigin: true,\n});\n\napp.use('/api', proxyMiddleware);\n\napp.listen(3000);\n\n// proxy and keep the same base path \"/api\"\n// http://127.0.0.1:3000/api/foo/bar -\u003e http://www.example.org/api/foo/bar\n```\n\n_All_ `http-proxy` [options](https://github.com/nodejitsu/node-http-proxy#options) can be used, along with some extra `http-proxy-middleware` [options](#options).\n\n## Table of Contents \u003c!-- omit in toc --\u003e\n\n\u003c!-- // spell-checker:disable --\u003e\n\n- [Install](#install)\n- [Basic usage](#basic-usage)\n- [Express Server Example](#express-server-example)\n  - [app.use(path, proxy)](#appusepath-proxy)\n- [Options](#options)\n  - [`pathFilter` (string, \\[\\]string, glob, \\[\\]glob, function)](#pathfilter-string-string-glob-glob-function)\n  - [`pathRewrite` (object/function)](#pathrewrite-objectfunction)\n  - [`router` (object/function)](#router-objectfunction)\n  - [`plugins` (Array)](#plugins-array)\n  - [`ejectPlugins` (boolean) default: `false`](#ejectplugins-boolean-default-false)\n  - [`logger` (Object)](#logger-object)\n- [`http-proxy` events](#http-proxy-events)\n- [`http-proxy` options](#http-proxy-options)\n- [WebSocket](#websocket)\n  - [External WebSocket upgrade](#external-websocket-upgrade)\n- [Intercept and manipulate requests](#intercept-and-manipulate-requests)\n- [Intercept and manipulate responses](#intercept-and-manipulate-responses)\n- [Node.js 17+: ECONNREFUSED issue with IPv6 and localhost (#705)](#nodejs-17-econnrefused-issue-with-ipv6-and-localhost-705)\n- [Debugging](#debugging)\n- [Working examples](#working-examples)\n- [Recipes](#recipes)\n- [Compatible servers](#compatible-servers)\n- [Tests](#tests)\n- [Changelog](#changelog)\n- [License](#license)\n\n\u003c!-- // spell-checker:enable --\u003e\n\n## Install\n\n```shell\nnpm install --save-dev http-proxy-middleware\n```\n\n## Basic usage\n\nCreate and configure a proxy middleware with: `createProxyMiddleware(config)`.\n\n```javascript\nconst { createProxyMiddleware } = require('http-proxy-middleware');\n\nconst apiProxy = createProxyMiddleware({\n  target: 'http://www.example.org',\n  changeOrigin: true,\n});\n\n// 'apiProxy' is now ready to be used as middleware in a server.\n```\n\n- **options.target**: target host to proxy to. _(protocol + host)_\n- **options.changeOrigin**: for virtual hosted sites\n\n- see full list of [`http-proxy-middleware` configuration options](#options)\n\n## Express Server Example\n\nAn example with `express` server.\n\n```javascript\n// include dependencies\nconst express = require('express');\nconst { createProxyMiddleware } = require('http-proxy-middleware');\n\nconst app = express();\n\n// create the proxy\n/** @type {import('http-proxy-middleware/dist/types').RequestHandler\u003cexpress.Request, express.Response\u003e} */\nconst exampleProxy = createProxyMiddleware({\n  target: 'http://www.example.org/api', // target host with the same base path\n  changeOrigin: true, // needed for virtual hosted sites\n});\n\n// mount `exampleProxy` in web server\napp.use('/api', exampleProxy);\napp.listen(3000);\n```\n\n### app.use(path, proxy)\n\nIf you want to use the server's `app.use` `path` parameter to match requests.\nUse `pathFilter` option to further include/exclude requests which you want to proxy.\n\n```javascript\napp.use(\n  createProxyMiddleware({\n    target: 'http://www.example.org/api',\n    changeOrigin: true,\n    pathFilter: '/api/proxy-only-this-path',\n  }),\n);\n```\n\n`app.use` documentation:\n\n- express: \u003chttp://expressjs.com/en/4x/api.html#app.use\u003e\n- connect: \u003chttps://github.com/senchalabs/connect#mount-middleware\u003e\n- polka: \u003chttps://github.com/lukeed/polka#usebase-fn\u003e\n\n## Options\n\nhttp-proxy-middleware options:\n\n### `pathFilter` (string, []string, glob, []glob, function)\n\nNarrow 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.\n\n- **path matching**\n\n  - `createProxyMiddleware({...})` - matches any path, all requests will be proxied when `pathFilter` is not configured.\n  - `createProxyMiddleware({ pathFilter: '/api', ...})` - matches paths starting with `/api`\n\n- **multiple path matching**\n\n  - `createProxyMiddleware({ pathFilter: ['/api', '/ajax', '/someotherpath'], ...})`\n\n- **wildcard path matching**\n\n  For fine-grained control you can use wildcard matching. Glob pattern matching is done by _micromatch_. Visit [micromatch](https://www.npmjs.com/package/micromatch) or [glob](https://www.npmjs.com/package/glob) for more globbing examples.\n\n  - `createProxyMiddleware({ pathFilter: '**', ...})` matches any path, all requests will be proxied.\n  - `createProxyMiddleware({ pathFilter: '**/*.html', ...})` matches any path which ends with `.html`\n  - `createProxyMiddleware({ pathFilter: '/*.html', ...})` matches paths directly under path-absolute\n  - `createProxyMiddleware({ pathFilter: '/api/**/*.html', ...})` matches requests ending with `.html` in the path of `/api`\n  - `createProxyMiddleware({ pathFilter: ['/api/**', '/ajax/**'], ...})` combine multiple patterns\n  - `createProxyMiddleware({ pathFilter: ['/api/**', '!**/bad.json'], ...})` exclusion\n\n  **Note**: In multiple path matching, you cannot use string paths and wildcard paths together.\n\n- **custom matching**\n\n  For full control you can provide a custom function to determine which requests should be proxied or not.\n\n  ```javascript\n  /**\n   * @return {Boolean}\n   */\n  const pathFilter = function (path, req) {\n    return path.match('^/api') \u0026\u0026 req.method === 'GET';\n  };\n\n  const apiProxy = createProxyMiddleware({\n    target: 'http://www.example.org',\n    pathFilter: pathFilter,\n  });\n  ```\n\n### `pathRewrite` (object/function)\n\nRewrite target's url path. Object-keys will be used as _RegExp_ to match paths.\n\n```javascript\n// rewrite path\npathRewrite: {'^/old/api' : '/new/api'}\n\n// remove path\npathRewrite: {'^/remove/api' : ''}\n\n// add base path\npathRewrite: {'^/' : '/basepath/'}\n\n// custom rewriting\npathRewrite: function (path, req) { return path.replace('/api', '/base/api') }\n\n// custom rewriting, returning Promise\npathRewrite: async function (path, req) {\n  const should_add_something = await httpRequestToDecideSomething(path);\n  if (should_add_something) path += \"something\";\n  return path;\n}\n```\n\n### `router` (object/function)\n\nRe-target `option.target` for specific requests.\n\n```javascript\n// Use `host` and/or `path` to match requests. First match will be used.\n// The order of the configuration matters.\nrouter: {\n    'integration.localhost:3000' : 'http://127.0.0.1:8001',  // host only\n    'staging.localhost:3000'     : 'http://127.0.0.1:8002',  // host only\n    'localhost:3000/api'         : 'http://127.0.0.1:8003',  // host + path\n    '/rest'                      : 'http://127.0.0.1:8004'   // path only\n}\n\n// Custom router function (string target)\nrouter: function(req) {\n    return 'http://127.0.0.1:8004';\n}\n\n// Custom router function (target object)\nrouter: function(req) {\n    return {\n        protocol: 'https:', // The : is required\n        host: '127.0.0.1',\n        port: 8004\n    };\n}\n\n// Asynchronous router function which returns promise\nrouter: async function(req) {\n    const url = await doSomeIO();\n    return url;\n}\n```\n\n### `plugins` (Array)\n\n```js\nconst simpleRequestLogger = (proxyServer, options) =\u003e {\n  proxyServer.on('proxyReq', (proxyReq, req, res) =\u003e {\n    console.log(`[HPM] [${req.method}] ${req.url}`); // outputs: [HPM] GET /users\n  });\n},\n\nconst config = {\n  target: `http://example.org`,\n  changeOrigin: true,\n  plugins: [simpleRequestLogger],\n};\n```\n\n### `ejectPlugins` (boolean) default: `false`\n\nIf you're not satisfied with the pre-configured plugins, you can eject them by configuring `ejectPlugins: true`.\n\nNOTE: register your own error handlers to prevent server from crashing.\n\n```js\n// eject default plugins and manually add them back\n\nconst {\n  debugProxyErrorsPlugin, // subscribe to proxy errors to prevent server from crashing\n  loggerPlugin, // log proxy events to a logger (ie. console)\n  errorResponsePlugin, // return 5xx response on proxy error\n  proxyEventsPlugin, // implements the \"on:\" option\n} = require('http-proxy-middleware');\n\ncreateProxyMiddleware({\n  target: `http://example.org`,\n  changeOrigin: true,\n  ejectPlugins: true,\n  plugins: [debugProxyErrorsPlugin, loggerPlugin, errorResponsePlugin, proxyEventsPlugin],\n});\n```\n\n### `logger` (Object)\n\nConfigure a logger to output information from http-proxy-middleware: ie. `console`, `winston`, `pino`, `bunyan`, `log4js`, etc...\n\nOnly `info`, `warn`, `error` are used internally for compatibility across different loggers.\n\nIf you use `winston`, make sure to enable interpolation: \u003chttps://github.com/winstonjs/winston#string-interpolation\u003e\n\nSee also logger recipes ([recipes/logger.md](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md)) for more details.\n\n```javascript\ncreateProxyMiddleware({\n  logger: console,\n});\n```\n\n## `http-proxy` events\n\nSubscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events) with the `on` option:\n\n```js\ncreateProxyMiddleware({\n  target: 'http://www.example.org',\n  on: {\n    proxyReq: (proxyReq, req, res) =\u003e {\n      /* handle proxyReq */\n    },\n    proxyRes: (proxyRes, req, res) =\u003e {\n      /* handle proxyRes */\n    },\n    error: (err, req, res) =\u003e {\n      /* handle error */\n    },\n  },\n});\n```\n\n- **option.on.error**: function, subscribe to http-proxy's `error` event for custom error handling.\n\n  ```javascript\n  function onError(err, req, res, target) {\n    res.writeHead(500, {\n      'Content-Type': 'text/plain',\n    });\n    res.end('Something went wrong. And we are reporting a custom error message.');\n  }\n  ```\n\n- **option.on.proxyRes**: function, subscribe to http-proxy's `proxyRes` event.\n\n  ```javascript\n  function onProxyRes(proxyRes, req, res) {\n    proxyRes.headers['x-added'] = 'foobar'; // add new header to response\n    delete proxyRes.headers['x-removed']; // remove header from response\n  }\n  ```\n\n- **option.on.proxyReq**: function, subscribe to http-proxy's `proxyReq` event.\n\n  ```javascript\n  function onProxyReq(proxyReq, req, res) {\n    // add custom header to request\n    proxyReq.setHeader('x-added', 'foobar');\n    // or log the req\n  }\n  ```\n\n- **option.on.proxyReqWs**: function, subscribe to http-proxy's `proxyReqWs` event.\n\n  ```javascript\n  function onProxyReqWs(proxyReq, req, socket, options, head) {\n    // add custom header\n    proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');\n  }\n  ```\n\n- **option.on.open**: function, subscribe to http-proxy's `open` event.\n\n  ```javascript\n  function onOpen(proxySocket) {\n    // listen for messages coming FROM the target here\n    proxySocket.on('data', hybridParseAndLogMessage);\n  }\n  ```\n\n- **option.on.close**: function, subscribe to http-proxy's `close` event.\n\n  ```javascript\n  function onClose(res, socket, head) {\n    // view disconnected websocket connections\n    console.log('Client disconnected');\n  }\n  ```\n\n## `http-proxy` options\n\nThe following options are provided by the underlying [http-proxy](https://github.com/nodejitsu/node-http-proxy#options) library.\n\n- **option.target**: url string to be parsed with the url module\n- **option.forward**: url string to be parsed with the url module\n- **option.agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects)\n- **option.ssl**: object to be passed to https.createServer()\n- **option.ws**: true/false: if you want to proxy websockets\n- **option.xfwd**: true/false, adds x-forward headers\n- **option.secure**: true/false, if you want to verify the SSL Certs\n- **option.toProxy**: true/false, passes the absolute URL as the `path` (useful for proxying to proxies)\n- **option.prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path\n- **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).\n- **option.localAddress** : Local interface string to bind for outgoing connections\n- **option.changeOrigin**: true/false, Default: false - changes the origin of the host header to the target URL\n- **option.preserveHeaderKeyCase**: true/false, Default: false - specify whether you want to keep letter case of response header key\n- **option.auth** : Basic authentication i.e. 'user:password' to compute an Authorization header.\n- **option.hostRewrite**: rewrites the location hostname on (301/302/307/308) redirects.\n- **option.autoRewrite**: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false.\n- **option.protocolRewrite**: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null.\n- **option.cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:\n\n  - `false` (default): disable cookie rewriting\n  - String: new domain, for example `cookieDomainRewrite: \"new.domain\"`. To remove the domain, use `cookieDomainRewrite: \"\"`.\n  - Object: mapping of domains to new domains, use `\"*\"` to match all domains.  \n    For example keep one domain unchanged, rewrite one domain and remove other domains:\n\n    ```json\n    cookieDomainRewrite: {\n      \"unchanged.domain\": \"unchanged.domain\",\n      \"old.domain\": \"new.domain\",\n      \"*\": \"\"\n    }\n    ```\n\n- **option.cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values:\n\n  - `false` (default): disable cookie rewriting\n  - String: new path, for example `cookiePathRewrite: \"/newPath/\"`. To remove the path, use `cookiePathRewrite: \"\"`. To set path to root use `cookiePathRewrite: \"/\"`.\n  - Object: mapping of paths to new paths, use `\"*\"` to match all paths.\n    For example, to keep one path unchanged, rewrite one path and remove other paths:\n\n    ```json\n    cookiePathRewrite: {\n      \"/unchanged.path/\": \"/unchanged.path/\",\n      \"/old.path/\": \"/new.path/\",\n      \"*\": \"\"\n    }\n    ```\n\n- **option.headers**: object, adds [request headers](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields). (Example: `{host:'www.example.org'}`)\n- **option.proxyTimeout**: timeout (in millis) when proxy receives no response from target\n- **option.timeout**: timeout (in millis) for incoming requests\n- **option.followRedirects**: true/false, Default: false - specify whether you want to follow redirects\n- **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\n- **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:\n\n  ```javascript\n  'use strict';\n\n  const streamify = require('stream-array');\n  const HttpProxy = require('http-proxy');\n  const proxy = new HttpProxy();\n\n  module.exports = (req, res, next) =\u003e {\n    proxy.web(\n      req,\n      res,\n      {\n        target: 'http://127.0.0.1:4003/',\n        buffer: streamify(req.rawBody),\n      },\n      next,\n    );\n  };\n  ```\n\n## WebSocket\n\n```javascript\n// verbose api\ncreateProxyMiddleware({ pathFilter: '/', target: 'http://echo.websocket.org', ws: true });\n```\n\n### External WebSocket upgrade\n\nIn 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.\n\n```javascript\nconst wsProxy = createProxyMiddleware({ target: 'ws://echo.websocket.org', changeOrigin: true });\n\nconst app = express();\napp.use(wsProxy);\n\nconst server = app.listen(3000);\nserver.on('upgrade', wsProxy.upgrade); // \u003c-- subscribe to http 'upgrade'\n```\n\n## Intercept and manipulate requests\n\nIntercept requests from downstream by defining `onProxyReq` in `createProxyMiddleware`.\n\nCurrently the only pre-provided request interceptor is `fixRequestBody`, which is used to fix proxied POST requests when `bodyParser` is applied before this middleware.\n\nExample:\n\n```javascript\nconst { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware');\n\nconst proxy = createProxyMiddleware({\n  /**\n   * Fix bodyParser\n   **/\n  on: {\n    proxyReq: fixRequestBody,\n  },\n});\n```\n\n## Intercept and manipulate responses\n\nIntercept responses from upstream with `responseInterceptor`. (Make sure to set `selfHandleResponse: true`)\n\nResponses which are compressed with `brotli`, `gzip` and `deflate` will be decompressed automatically. The response will be returned as `buffer` ([docs](https://nodejs.org/api/buffer.html)) which you can manipulate.\n\nWith `buffer`, response manipulation is not limited to text responses (html/css/js, etc...); image manipulation will be possible too. ([example](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md#manipulate-image-response))\n\nNOTE: `responseInterceptor` disables streaming of target's response.\n\nExample:\n\n```javascript\nconst { createProxyMiddleware, responseInterceptor } = require('http-proxy-middleware');\n\nconst proxy = createProxyMiddleware({\n  /**\n   * IMPORTANT: avoid res.end being called automatically\n   **/\n  selfHandleResponse: true, // res.end() will be called internally by responseInterceptor()\n\n  /**\n   * Intercept response and replace 'Hello' with 'Goodbye'\n   **/\n  on: {\n    proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) =\u003e {\n      const response = responseBuffer.toString('utf8'); // convert buffer to string\n      return response.replace('Hello', 'Goodbye'); // manipulate response and return the result\n    }),\n  },\n});\n```\n\nCheck out [interception recipes](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md#readme) for more examples.\n\n## Node.js 17+: ECONNREFUSED issue with IPv6 and localhost ([#705](https://github.com/chimurai/http-proxy-middleware/issues/705))\n\nNode.js 17+ no longer prefers IPv4 over IPv6 for DNS lookups.\nE.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).\n\nIf your target server only accepts IPv4 connections, trying to proxy to `localhost` will fail if resolved to `::1` (IPv6).\n\nWays to solve it:\n\n- Change `target: \"http://localhost\"` to `target: \"http://127.0.0.1\"` (IPv4).\n- Change the target server to (also) accept IPv6 connections.\n- Add this flag when running `node`: `node index.js --dns-result-order=ipv4first`. (Not recommended.)\n\n\u003e Note: There’s a thing called [Happy Eyeballs](https://en.wikipedia.org/wiki/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.\n\n## Debugging\n\nConfigure the `DEBUG` environment variable enable debug logging.\n\nSee [`debug`](https://github.com/debug-js/debug#readme) project for more options.\n\n```shell\nDEBUG=http-proxy-middleware* node server.js\n\n$ http-proxy-middleware proxy created +0ms\n$ http-proxy-middleware proxying request to target: 'http://www.example.org' +359ms\n```\n\n## Working examples\n\nView and play around with [working examples](https://github.com/chimurai/http-proxy-middleware/tree/master/examples).\n\n- Browser-Sync ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/browser-sync/index.js))\n- express ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/express/index.js))\n- connect ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/connect/index.js))\n- WebSocket ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/websocket/index.js))\n- Response Manipulation ([example source](https://github.com/chimurai/http-proxy-middleware/blob/master/examples/response-interceptor/index.js))\n\n## Recipes\n\nView the [recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes) for common use cases.\n\n## Compatible servers\n\n`http-proxy-middleware` is compatible with the following servers:\n\n- [connect](https://www.npmjs.com/package/connect)\n- [express](https://www.npmjs.com/package/express)\n- [next.js](https://www.npmjs.com/package/next)\n- [fastify](https://www.npmjs.com/package/fastify)\n- [browser-sync](https://www.npmjs.com/package/browser-sync)\n- [lite-server](https://www.npmjs.com/package/lite-server)\n- [polka](https://github.com/lukeed/polka)\n- [grunt-contrib-connect](https://www.npmjs.com/package/grunt-contrib-connect)\n- [grunt-browser-sync](https://www.npmjs.com/package/grunt-browser-sync)\n- [gulp-connect](https://www.npmjs.com/package/gulp-connect)\n- [gulp-webserver](https://www.npmjs.com/package/gulp-webserver)\n\nSample implementations can be found in the [server recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes/servers.md).\n\n## Tests\n\nRun the test suite:\n\n```bash\n# install dependencies\n$ yarn\n\n# linting\n$ yarn lint\n$ yarn lint:fix\n\n# building (compile typescript to js)\n$ yarn build\n\n# unit tests\n$ yarn test\n\n# code coverage\n$ yarn cover\n\n# check spelling mistakes\n$ yarn spellcheck\n```\n\n## Changelog\n\n- [View changelog](https://github.com/chimurai/http-proxy-middleware/blob/master/CHANGELOG.md)\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2015-2025 Steven Chim\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchimurai%2Fhttp-proxy-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchimurai%2Fhttp-proxy-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchimurai%2Fhttp-proxy-middleware/lists"}