{"name":"http-proxy-middleware","version":"3.0.6","keywords":["reverse","proxy","middleware","http","https","connect","express","fastify","polka","next.js","browser-sync","gulp","grunt-contrib-connect","websocket","ws","cors"],"author":{"name":"Steven Chim"},"license":"MIT","_id":"http-proxy-middleware@3.0.6","maintainers":[{"name":"chimurai","email":"stevenchim@gmail.com"}],"homepage":"https://github.com/chimurai/http-proxy-middleware#readme","bugs":{"url":"https://github.com/chimurai/http-proxy-middleware/issues"},"dist":{"shasum":"5c11d604f94bef39c30f8f3a5e1ed571634c3ca0","tarball":"http://registry-npm.ywwl.com/http-proxy-middleware/download/http-proxy-middleware-3.0.6.tgz","fileCount":63,"integrity":"sha512-jhO3QfahaHWfQjEnyGW0vpYIYaXcnA6FEfehrBthOokGppvmI6zcV+1yb6TWn3vyeh8yQUoEqH51DNHOCjivxg==","signatures":[{"sig":"MEUCIQDMwzQsCbcx6KK75Eqv7vf5zbcNYU1ir6FN2LyWBg2huQIgDiKCUjpHu93vIyXEBw4N7MS3CUMThog+8PwqIA28hhc=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/http-proxy-middleware@3.0.6","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":83944,"size":24140,"noattachment":false,"key":"/http-proxy-middleware/-/http-proxy-middleware-3.0.6.tgz"},"main":"dist/index.js","type":"commonjs","types":"dist/index.d.ts","engines":{"node":"^14.18.0 || ^16.10.0 || >=18.0.0"},"gitHead":"ea0bb98867bda354b759e92ce1933ab43cbbbcf8","scripts":{"lint":"yarn prettier && yarn eslint","test":"jest","build":"tsc --build","clean":"rm -rf dist coverage tsconfig.tsbuildinfo .eslintcache","eslint":"eslint '{src,test,examples}/**/*.{js,ts}' --cache","prepack":"yarn clean && yarn test && yarn build","prepare":"husky && patch-package","coverage":"jest --coverage","lint:fix":"yarn prettier:fix && yarn eslint:fix","prettier":"prettier --list-different \"**/*.{js,ts,md,yml,json,html}\"","eslint:fix":"yarn eslint --fix","spellcheck":"npx --yes cspell --show-context --show-suggestions '**/*.*'","install:all":"yarn && (cd examples && yarn)","prettier:fix":"prettier --write \"**/*.{js,ts,md,yml,json,html}\""},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","approver":{"name":"chimurai","email":"stevenchim@gmail.com"},"trustedPublisher":{"id":"github","oidcConfigId":"oidc:429f9e15-9ddd-4c60-86e0-c582e4a4c75f"}},"commitlint":{"extends":["@commitlint/config-conventional"]},"repository":{"url":"git+https://github.com/chimurai/http-proxy-middleware.git","type":"git"},"_npmVersion":"11.16.0","description":"The one-liner node.js proxy middleware for connect, express, next.js and more","directories":{},"resolutions":{"patch-package/**/tmp":"^0.2.4"},"_nodeVersion":"24.16.0","dependencies":{"debug":"^4.3.6","is-glob":"^4.0.3","http-proxy":"^1.18.1","micromatch":"^4.0.8","is-plain-object":"^5.0.0","@types/http-proxy":"^1.17.15"},"publishConfig":{"provenance":true},"_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"ws":"8.19.0","jest":"30.2.0","open":"8.4.2","husky":"9.1.7","eslint":"10.0.2","express":"5.2.1","globals":"17.3.0","mockttp":"4.2.1","ts-jest":"29.4.6","get-port":"5.1.1","prettier":"3.8.1","@types/ws":"8.18.1","supertest":"7.2.2","@eslint/js":"10.0.1","pkg-pr-new":"0.0.65","typescript":"5.9.3","@types/jest":"30.0.0","@types/node":"24.10.2","body-parser":"2.2.2","lint-staged":"16.3.0","@types/debug":"4.1.12","@types/eslint":"9.6.1","patch-package":"8.0.1","@types/express":"5.0.6","@types/is-glob":"4.0.4","@commitlint/cli":"20.4.2","@types/supertest":"7.2.0","@types/micromatch":"4.0.10","typescript-eslint":"8.56.1","@commitlint/config-conventional":"20.4.2","@trivago/prettier-plugin-sort-imports":"6.0.2"},"_npmOperationalInternal":{"tmp":"tmp/http-proxy-middleware_3.0.6_1780758050299_0.14364001903999934","host":"s3://npm-registry-packages-npm-production"},"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&logo=github-actions&logoColor=white&style=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&logo=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&style=flat-square&logo=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), [hono](https://github.com/honojs/hono) and [many more](#compatible-servers).\n\nPowered by [`httpxy`](https://github.com/unjs/httpxy). A maintained version of [http-proxy](https://github.com/http-party/node-http-proxy).\n\n## ⚠️ Note <!-- omit in toc -->\n\nThis page is showing documentation for version **v4.x.x** ([release notes](https://github.com/chimurai/http-proxy-middleware/releases))\n\nFor older documentation:\n\n- [v3.0.5](https://github.com/chimurai/http-proxy-middleware/tree/v3.0.5#readme)\n- [v2.0.4](https://github.com/chimurai/http-proxy-middleware/tree/v2.0.4#readme)\n- [v0.21.0](https://github.com/chimurai/http-proxy-middleware/tree/v0.21.0#readme)\n\n## TL;DR <!-- omit in toc -->\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 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<Request, Response>({\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 -> http://www.example.org/api/foo/bar\n```\n\n_All_ `httpxy` [options](https://github.com/unjs/httpxy#options) can be used, along with some extra `http-proxy-middleware` [options](#options).\n\n## Table of Contents <!-- omit in toc -->\n\n<!-- // spell-checker:disable -->\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- [`definePlugin` helper](#defineplugin-helper)\n  - [`logger` (Object)](#logger-object)\n- [`httpxy` events](#httpxy-events)\n- [`httpxy` options](#httpxy-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<!-- // spell-checker:enable -->\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\nimport { createProxyMiddleware } from '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\nimport express from 'express';\nimport { createProxyMiddleware } from 'http-proxy-middleware';\n\nconst app = express();\n\n// create the proxy\n/** @type {import('http-proxy-middleware').RequestHandler<import('express').Request, import('express').Response>} */\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: <http://expressjs.com/en/4x/api.html#app.use>\n- connect: <https://github.com/senchalabs/connect#mount-middleware>\n- polka: <https://github.com/lukeed/polka#usebase-fn>\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  - `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  - `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  - `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') && 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, res, options) { return path.replace('/api', '/base/api') }\n\n// custom rewriting, returning Promise\npathRewrite: async function (path, req, res, options) {\n  const should_add_something = await httpRequestToDecideSomething(path);\n  if (should_add_something) path += \"something\";\n  return path;\n}\n\n// `res` is undefined in WebSocket upgrade flows.\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, res, options) {\n    return 'http://127.0.0.1:8004';\n}\n\n// Custom router function (target object)\nrouter: function(req, res, options) {\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, res, options) {\n    const url = await doSomeIO();\n    return url;\n}\n\n// NOTE: `res` is undefined in WebSocket upgrade flows.\n```\n\n### `plugins` (Array)\n\n```js\nconst simpleRequestLogger = (proxyServer, options) => {\n  proxyServer.on('proxyReq', (proxyReq, req, res) => {\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\nimport {\n  debugProxyErrorsPlugin, // subscribe to proxy errors to prevent server from crashing\n  errorResponsePlugin, // return 5xx response on proxy error\n  loggerPlugin, // log proxy events to a logger (ie. console)\n  proxyEventsPlugin, // implements the \"on:\" option\n} from '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## `definePlugin` helper\n\nCreate your own `http-proxy-middleware` plugin.\n\n(Default plugins are created with `definePlugin`)\n\n```ts\nimport { createProxyMiddleware, definePlugin } from 'http-proxy-middleware';\n\nconst myPlugin = definePlugin((proxyServer, options) => {\n  // plugin implementation\n});\n\n// use configure and use plugin\ncreateProxyMiddleware({\n  target: `http://example.org`,\n  plugins: [myPlugin],\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: <https://github.com/winstonjs/winston#string-interpolation>\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## `httpxy` events\n\nSubscribe to [httpxy events](https://github.com/unjs/httpxy#events) with the `on` option:\n\n```js\ncreateProxyMiddleware({\n  target: 'http://www.example.org',\n  on: {\n    proxyReq: (proxyReq, req, res) => {\n      /* handle proxyReq */\n    },\n    proxyRes: (proxyRes, req, res) => {\n      /* handle proxyRes */\n    },\n    error: (err, req, res) => {\n      /* handle error */\n    },\n  },\n});\n```\n\n- **option.on.error**: function, subscribe to httpxy'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 httpxy'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 httpxy'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 httpxy'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 httpxy'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 httpxy'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## `httpxy` options\n\nThe following options are provided by the underlying [httpxy](https://github.com/unjs/httpxy#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  - `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    ```jsonc\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  - `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    ```jsonc\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  import { createProxyServer } from 'httpxy';\n  import streamify from 'stream-array';\n\n  const proxy = createProxyServer();\n\n  export default function proxyWithBody(req, res, next) {\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\nSee [recipes/websocket.md](recipes/websocket.md) for more examples.\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 an 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\nWhen the same middleware instance is attached to multiple servers and `ws: true` is used, each server needs its own initial HTTP request before upgrades are auto-subscribed.\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); // <-- 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\nimport { createProxyMiddleware, fixRequestBody } from '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\nimport { createProxyMiddleware, responseInterceptor } from '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) => {\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) 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\nAdditional IPv6 notes:\n\n- Unspecified IPv6 host `http://[::]:port` is normalized to loopback (`::1`) to reach local listeners.\n\n> 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- [hono](https://www.npmjs.com/package/@hono/node-server)\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 coverage\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-2026 Steven Chim\n","publish_time":1780758050378,"_cnpm_publish_time":1780758050378,"dist-tags":{"beta":"4.1.0-beta.2","latest":"4.2.1","v2-beta":"2.0.10-beta.0","v2-latest":"2.0.11","v3-latest":"3.0.10"}}