feat: Passwordless cross-device authentication

- Arkitektur: docs/auth/passwordless-architecture.md
- Backend: iom/quixzoom-auth-service/ (FastAPI + Redis)
- Webb: quixzoom-market-pages/se/login/ (QR-kod + polling)
- App: iom/quixzoom-app/src/features/auth/ (push + deep links)

Flöde: QR-kod → app-godkännande → webb-inloggad
This commit is contained in:
Bernt
2026-07-07 07:11:50 +00:00
parent 4aa984ad74
commit 6989a98d75
61843 changed files with 5491611 additions and 872231 deletions
+22
View File
@@ -0,0 +1,22 @@
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.
+671
View File
@@ -0,0 +1,671 @@
# http-proxy-middleware
[![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)
[![Coveralls](https://img.shields.io/coveralls/chimurai/http-proxy-middleware.svg?style=flat-square&logo=coveralls)](https://coveralls.io/r/chimurai/http-proxy-middleware)
[![Known Vulnerabilities](https://snyk.io/test/github/chimurai/http-proxy-middleware/badge.svg)](https://snyk.io/test/github/chimurai/http-proxy-middleware)
[![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)
Node.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).
Powered by [`httpxy`](https://github.com/unjs/httpxy). A maintained version of [http-proxy](https://github.com/http-party/node-http-proxy).
## ⚠️ Note <!-- omit in toc -->
This page is showing documentation for version **v4.x.x** ([release notes](https://github.com/chimurai/http-proxy-middleware/releases))
For older documentation:
- [v3.0.5](https://github.com/chimurai/http-proxy-middleware/tree/v3.0.5#readme)
- [v2.0.4](https://github.com/chimurai/http-proxy-middleware/tree/v2.0.4#readme)
- [v0.21.0](https://github.com/chimurai/http-proxy-middleware/tree/v0.21.0#readme)
## TL;DR <!-- omit in toc -->
Proxy `/api` requests to `http://www.example.org`
:bulb: **Tip:** Set the option `changeOrigin` to `true` for [name-based virtual hosted sites](http://en.wikipedia.org/wiki/Virtual_hosting#Name-based).
```typescript
// typescript
import express from 'express';
import type { NextFunction, Request, Response } from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
import type { Filter, Options, RequestHandler } from 'http-proxy-middleware';
const app = express();
const proxyMiddleware = createProxyMiddleware<Request, Response>({
target: 'http://www.example.org/api',
changeOrigin: true,
});
app.use('/api', proxyMiddleware);
app.listen(3000);
// proxy and keep the same base path "/api"
// http://127.0.0.1:3000/api/foo/bar -> http://www.example.org/api/foo/bar
```
_All_ `httpxy` [options](https://github.com/unjs/httpxy#options) can be used, along with some extra `http-proxy-middleware` [options](#options).
## Table of Contents <!-- omit in toc -->
<!-- // spell-checker:disable -->
- [Install](#install)
- [Basic usage](#basic-usage)
- [Express Server Example](#express-server-example)
- [app.use(path, proxy)](#appusepath-proxy)
- [Options](#options)
- [`pathFilter` (string, \[\]string, glob, \[\]glob, function)](#pathfilter-string-string-glob-glob-function)
- [`pathRewrite` (object/function)](#pathrewrite-objectfunction)
- [`router` (object/function)](#router-objectfunction)
- [`plugins` (Array)](#plugins-array)
- [`ejectPlugins` (boolean) default: `false`](#ejectplugins-boolean-default-false)
- [`definePlugin` helper](#defineplugin-helper)
- [`logger` (Object)](#logger-object)
- [`httpxy` events](#httpxy-events)
- [`httpxy` options](#httpxy-options)
- [WebSocket](#websocket)
- [External WebSocket upgrade](#external-websocket-upgrade)
- [Intercept and manipulate requests](#intercept-and-manipulate-requests)
- [Intercept and manipulate responses](#intercept-and-manipulate-responses)
- [Node.js 17+: ECONNREFUSED issue with IPv6 and localhost (#705)](#nodejs-17-econnrefused-issue-with-ipv6-and-localhost-705)
- [Debugging](#debugging)
- [Working examples](#working-examples)
- [Recipes](#recipes)
- [Compatible servers](#compatible-servers)
- [Tests](#tests)
- [Changelog](#changelog)
- [License](#license)
<!-- // spell-checker:enable -->
## Install
```shell
npm install --save-dev http-proxy-middleware
```
## Basic usage
Create and configure a proxy middleware with: `createProxyMiddleware(config)`.
```javascript
import { createProxyMiddleware } from 'http-proxy-middleware';
const apiProxy = createProxyMiddleware({
target: 'http://www.example.org',
changeOrigin: true,
});
// '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](#options)
## Express Server Example
An example with `express` server.
```javascript
// include dependencies
import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
const app = express();
// create the proxy
/** @type {import('http-proxy-middleware').RequestHandler<import('express').Request, import('express').Response>} */
const exampleProxy = createProxyMiddleware({
target: 'http://www.example.org/api', // target host with the same base path
changeOrigin: true, // needed for virtual hosted sites
});
// mount `exampleProxy` in web server
app.use('/api', exampleProxy);
app.listen(3000);
```
### app.use(path, proxy)
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.
```javascript
app.use(
createProxyMiddleware({
target: 'http://www.example.org/api',
changeOrigin: true,
pathFilter: '/api/proxy-only-this-path',
}),
);
```
`app.use` documentation:
- express: <http://expressjs.com/en/4x/api.html#app.use>
- connect: <https://github.com/senchalabs/connect#mount-middleware>
- polka: <https://github.com/lukeed/polka#usebase-fn>
## Options
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](https://www.npmjs.com/package/micromatch) or [glob](https://www.npmjs.com/package/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-absolute
- `createProxyMiddleware({ pathFilter: '/api/**/*.html', ...})` matches requests ending with `.html` in the path of `/api`
- `createProxyMiddleware({ pathFilter: ['/api/**', '/ajax/**'], ...})` combine multiple patterns
- `createProxyMiddleware({ pathFilter: ['/api/**', '!**/bad.json'], ...})` exclusion
**Note**: 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.
```javascript
/**
* @return {Boolean}
*/
const pathFilter = function (path, req) {
return path.match('^/api') && req.method === 'GET';
};
const apiProxy = createProxyMiddleware({
target: 'http://www.example.org',
pathFilter: pathFilter,
});
```
### `pathRewrite` (object/function)
Rewrite target's url path. Object-keys will be used as _RegExp_ to match paths.
```javascript
// rewrite path
pathRewrite: {'^/old/api' : '/new/api'}
// remove path
pathRewrite: {'^/remove/api' : ''}
// add base path
pathRewrite: {'^/' : '/basepath/'}
// custom rewriting
pathRewrite: function (path, req, res, options) { return path.replace('/api', '/base/api') }
// custom rewriting, returning Promise
pathRewrite: async function (path, req, res, options) {
const should_add_something = await httpRequestToDecideSomething(path);
if (should_add_something) path += "something";
return path;
}
// `res` is undefined in WebSocket upgrade flows.
```
### `router` (object/function)
Re-target `option.target` for specific requests.
```javascript
// Use `host` and/or `path` to match requests. First match will be used.
// The order of the configuration matters.
router: {
'integration.localhost:3000' : 'http://127.0.0.1:8001', // host only
'staging.localhost:3000' : 'http://127.0.0.1:8002', // host only
'localhost:3000/api' : 'http://127.0.0.1:8003', // host + path
'/rest' : 'http://127.0.0.1:8004' // path only
}
// Custom router function (string target)
router: function(req, res, options) {
return 'http://127.0.0.1:8004';
}
// Custom router function (target object)
router: function(req, res, options) {
return {
protocol: 'https:', // The : is required
host: '127.0.0.1',
port: 8004
};
}
// Asynchronous router function which returns promise
router: async function(req, res, options) {
const url = await doSomeIO();
return url;
}
// NOTE: `res` is undefined in WebSocket upgrade flows.
```
### `plugins` (Array)
```js
const simpleRequestLogger = (proxyServer, options) => {
proxyServer.on('proxyReq', (proxyReq, req, res) => {
console.log(`[HPM] [${req.method}] ${req.url}`); // outputs: [HPM] GET /users
});
},
const config = {
target: `http://example.org`,
changeOrigin: true,
plugins: [simpleRequestLogger],
};
```
### `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.
```js
// eject default plugins and manually add them back
import {
debugProxyErrorsPlugin, // subscribe to proxy errors to prevent server from crashing
errorResponsePlugin, // return 5xx response on proxy error
loggerPlugin, // log proxy events to a logger (ie. console)
proxyEventsPlugin, // implements the "on:" option
} from 'http-proxy-middleware';
createProxyMiddleware({
target: `http://example.org`,
changeOrigin: true,
ejectPlugins: true,
plugins: [debugProxyErrorsPlugin, loggerPlugin, errorResponsePlugin, proxyEventsPlugin],
});
```
## `definePlugin` helper
Create your own `http-proxy-middleware` plugin.
(Default plugins are created with `definePlugin`)
```ts
import { createProxyMiddleware, definePlugin } from 'http-proxy-middleware';
const myPlugin = definePlugin((proxyServer, options) => {
// plugin implementation
});
// use configure and use plugin
createProxyMiddleware({
target: `http://example.org`,
plugins: [myPlugin],
});
```
### `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](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md)) for more details.
```javascript
createProxyMiddleware({
logger: console,
});
```
## `httpxy` events
Subscribe to [httpxy events](https://github.com/unjs/httpxy#events) with the `on` option:
```js
createProxyMiddleware({
target: 'http://www.example.org',
on: {
proxyReq: (proxyReq, req, res) => {
/* handle proxyReq */
},
proxyRes: (proxyRes, req, res) => {
/* handle proxyRes */
},
error: (err, req, res) => {
/* handle error */
},
},
});
```
- **option.on.error**: function, subscribe to httpxy's `error` event for custom error handling.
```javascript
function onError(err, req, res, target) {
res.writeHead(500, {
'Content-Type': 'text/plain',
});
res.end('Something went wrong. And we are reporting a custom error message.');
}
```
- **option.on.proxyRes**: function, subscribe to httpxy's `proxyRes` event.
```javascript
function onProxyRes(proxyRes, req, res) {
proxyRes.headers['x-added'] = 'foobar'; // add new header to response
delete proxyRes.headers['x-removed']; // remove header from response
}
```
- **option.on.proxyReq**: function, subscribe to httpxy's `proxyReq` event.
```javascript
function onProxyReq(proxyReq, req, res) {
// add custom header to request
proxyReq.setHeader('x-added', 'foobar');
// or log the req
}
```
- **option.on.proxyReqWs**: function, subscribe to httpxy's `proxyReqWs` event.
```javascript
function onProxyReqWs(proxyReq, req, socket, options, head) {
// add custom header
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
}
```
- **option.on.open**: function, subscribe to httpxy's `open` event.
```javascript
function onOpen(proxySocket) {
// listen for messages coming FROM the target here
proxySocket.on('data', hybridParseAndLogMessage);
}
```
- **option.on.close**: function, subscribe to httpxy's `close` event.
```javascript
function onClose(res, socket, head) {
// view disconnected websocket connections
console.log('Client disconnected');
}
```
## `httpxy` options
The following options are provided by the underlying [httpxy](https://github.com/unjs/httpxy#options) 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](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_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:
```jsonc
cookieDomainRewrite: {
"unchanged.domain": "unchanged.domain",
"old.domain": "new.domain",
"*": ""
}
```
- **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:
```jsonc
cookiePathRewrite: {
"/unchanged.path/": "/unchanged.path/",
"/old.path/": "/new.path/",
"*": ""
}
```
- **option.headers**: object, adds [request headers](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields). (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:
```javascript
import { createProxyServer } from 'httpxy';
import streamify from 'stream-array';
const proxy = createProxyServer();
export default function proxyWithBody(req, res, next) {
proxy.web(
req,
res,
{
target: 'http://127.0.0.1:4003/',
buffer: streamify(req.rawBody),
},
next,
);
}
```
## WebSocket
See [recipes/websocket.md](recipes/websocket.md) for more examples.
```javascript
// verbose api
createProxyMiddleware({ pathFilter: '/', target: 'http://echo.websocket.org', ws: true });
```
### External WebSocket upgrade
In 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.
When 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.
```javascript
const wsProxy = createProxyMiddleware({ target: 'ws://echo.websocket.org', changeOrigin: true });
const app = express();
app.use(wsProxy);
const server = app.listen(3000);
server.on('upgrade', wsProxy.upgrade); // <-- subscribe to http 'upgrade'
```
## Intercept and manipulate requests
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:
```javascript
import { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware';
const proxy = createProxyMiddleware({
/**
* Fix bodyParser
**/
on: {
proxyReq: fixRequestBody,
},
});
```
## Intercept and manipulate responses
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](https://nodejs.org/api/buffer.html)) 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](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md#manipulate-image-response))
NOTE: `responseInterceptor` disables streaming of target's response.
Example:
```javascript
import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
const proxy = createProxyMiddleware({
/**
* IMPORTANT: avoid res.end being called automatically
**/
selfHandleResponse: true, // res.end() will be called internally by responseInterceptor()
/**
* Intercept response and replace 'Hello' with 'Goodbye'
**/
on: {
proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
const response = responseBuffer.toString('utf8'); // convert buffer to string
return response.replace('Hello', 'Goodbye'); // manipulate response and return the result
}),
},
});
```
Check out [interception recipes](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md) for more examples.
## Node.js 17+: ECONNREFUSED issue with IPv6 and localhost ([#705](https://github.com/chimurai/http-proxy-middleware/issues/705))
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:
- Change `target: "http://localhost"` to `target: "http://127.0.0.1"` (IPv4).
- Change the target server to (also) accept IPv6 connections.
- Add this flag when running `node`: `node index.js --dns-result-order=ipv4first`. (Not recommended.)
Additional IPv6 notes:
- Unspecified IPv6 host `http://[::]:port` is normalized to loopback (`::1`) to reach local listeners.
> Note: Theres 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 doesnt have, but explains why for example `curl` can connect.
## Debugging
Configure the `DEBUG` environment variable enable debug logging.
See [`debug`](https://github.com/debug-js/debug#readme) project for more options.
```shell
DEBUG=http-proxy-middleware* node server.js
$ http-proxy-middleware proxy created +0ms
$ http-proxy-middleware proxying request to target: 'http://www.example.org' +359ms
```
## Working examples
View and play around with [working examples](https://github.com/chimurai/http-proxy-middleware/tree/master/examples).
- Browser-Sync ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/browser-sync/index.js))
- express ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/express/index.js))
- connect ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/connect/index.js))
- WebSocket ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/websocket/index.js))
- Response Manipulation ([example source](https://github.com/chimurai/http-proxy-middleware/blob/master/examples/response-interceptor/index.js))
## Recipes
View the [recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes) for common use cases.
## Compatible servers
`http-proxy-middleware` is compatible with the following servers:
- [connect](https://www.npmjs.com/package/connect)
- [express](https://www.npmjs.com/package/express)
- [hono](https://www.npmjs.com/package/@hono/node-server)
- [next.js](https://www.npmjs.com/package/next)
- [fastify](https://www.npmjs.com/package/fastify)
- [browser-sync](https://www.npmjs.com/package/browser-sync)
- [lite-server](https://www.npmjs.com/package/lite-server)
- [polka](https://github.com/lukeed/polka)
- [grunt-contrib-connect](https://www.npmjs.com/package/grunt-contrib-connect)
- [grunt-browser-sync](https://www.npmjs.com/package/grunt-browser-sync)
- [gulp-connect](https://www.npmjs.com/package/gulp-connect)
- [gulp-webserver](https://www.npmjs.com/package/gulp-webserver)
Sample implementations can be found in the [server recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes/servers.md).
## Tests
Run the test suite:
```bash
# install dependencies
$ yarn
# linting
$ yarn lint
$ yarn lint:fix
# building (compile typescript to js)
$ yarn build
# unit tests
$ yarn test
# code coverage
$ yarn coverage
# check spelling mistakes
$ yarn spellcheck
```
## Changelog
- [View changelog](https://github.com/chimurai/http-proxy-middleware/blob/master/CHANGELOG.md)
## License
The MIT License (MIT)
Copyright (c) 2015-2026 Steven Chim
+3
View File
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Options } from './types.js';
export declare function verifyConfig<TReq extends http.IncomingMessage, TRes extends http.ServerResponse>(options: Options<TReq, TRes>): void;
+6
View File
@@ -0,0 +1,6 @@
import { HttpProxyMiddlewareError } from './errors.js';
export function verifyConfig(options) {
if (!options.target && !options.router) {
throw new HttpProxyMiddlewareError('[HPM] Missing "target" option. Example: {target: "http://www.example.org"}', 'ERR_CONFIG_FACTORY_TARGET_MISSING');
}
}
+5
View File
@@ -0,0 +1,5 @@
import createDebug from 'debug';
/**
* Debug instance with the given namespace: http-proxy-middleware
*/
export declare const Debug: createDebug.Debugger;
+5
View File
@@ -0,0 +1,5 @@
import createDebug from 'debug';
/**
* Debug instance with the given namespace: http-proxy-middleware
*/
export const Debug = createDebug('http-proxy-middleware');
+4
View File
@@ -0,0 +1,4 @@
export declare class HttpProxyMiddlewareError extends Error {
code: string;
constructor(message: string, code: string);
}
+15
View File
@@ -0,0 +1,15 @@
export class HttpProxyMiddlewareError extends Error {
code;
constructor(message, code) {
super(message);
// add custom `code` property
// so this can be used in src/plugins/default/error-response-plugin.ts to determine the status code to return
this.code = code;
// set the correct name for the error class
this.name = this.constructor.name;
// maintain proper stack trace (V8 environments)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
+28
View File
@@ -0,0 +1,28 @@
import type { HttpBindings } from '@hono/node-server';
import type { MiddlewareHandler } from 'hono';
import { type Options } from './index.js';
/**
* Creates a Hono middleware that proxies requests using http-proxy-middleware.
*
* @remarks
* This middleware requires Hono to be running on Node.js via `@hono/node-server`.
* It uses `c.env.incoming` and `c.env.outgoing` which are only available with `HttpBindings`.
*
* @experimental This API is experimental and may change without a major version bump.
*
* @example
* ```ts
* import { serve } from '@hono/node-server';
* import { Hono } from 'hono';
* import { createHonoProxyMiddleware } from 'http-proxy-middleware/hono';
*
* const app = new Hono();
* app.use('/api', createHonoProxyMiddleware({ target: 'http://example.com', changeOrigin: true }));
* serve(app);
* ```
*
* @since 4.0.0
*/
export declare function createHonoProxyMiddleware(options: Options): MiddlewareHandler<{
Bindings: HttpBindings;
}>;
+45
View File
@@ -0,0 +1,45 @@
import { createProxyMiddleware } from './index.js';
import { getLogger } from './logger.js';
/**
* Creates a Hono middleware that proxies requests using http-proxy-middleware.
*
* @remarks
* This middleware requires Hono to be running on Node.js via `@hono/node-server`.
* It uses `c.env.incoming` and `c.env.outgoing` which are only available with `HttpBindings`.
*
* @experimental This API is experimental and may change without a major version bump.
*
* @example
* ```ts
* import { serve } from '@hono/node-server';
* import { Hono } from 'hono';
* import { createHonoProxyMiddleware } from 'http-proxy-middleware/hono';
*
* const app = new Hono();
* app.use('/api', createHonoProxyMiddleware({ target: 'http://example.com', changeOrigin: true }));
* serve(app);
* ```
*
* @since 4.0.0
*/
export function createHonoProxyMiddleware(options) {
const proxy = createProxyMiddleware(options);
const logger = getLogger(options);
return (c, next) => {
return new Promise((resolve, reject) => {
proxy(c.env.incoming, c.env.outgoing, (err) => {
if (err) {
reject(err);
}
else {
resolve();
}
});
})
.then(() => next())
.catch((err) => {
logger.error('Proxy error:', err);
return c.text('Proxy Error', 500);
});
};
}
+79
View File
@@ -0,0 +1,79 @@
import type * as http from 'node:http';
import type { NextFunction, Options, RequestHandler } from './types.js';
/**
* Create proxy middleware for Express-like servers. ([list of servers with examples](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md))
*
* @example Basic proxy to a single target.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* changeOrigin: true,
* });
* ```
*
* @example Proxy only matching paths and rewrite the forwarded path.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://localhost:3000',
* pathFilter: '/api',
* pathRewrite: {
* '^/api/': '/',
* },
* });
* ```
*
* @example Native path rewrite by mounting at a route (alternative to `pathRewrite`).
* ```ts
* import express from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const app = express();
* app.use(
* '/users',
* createProxyMiddleware({
* target: 'http://jsonplaceholder.typicode.com/users',
* changeOrigin: true,
* }),
* );
* ```
*
* @example Use framework-specific request/response types (Express).
* ```ts
* import type { Request, Response } from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware<Request, Response>({
* target: 'http://www.example.org/api',
* changeOrigin: true,
* });
* ```
*
* @example Intercept and modify a proxied response body.
* ```ts
* import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* selfHandleResponse: true,
* on: {
* proxyRes: responseInterceptor(async (responseBuffer) => {
* const response = responseBuffer.toString('utf8');
* return response.replace('Hello', 'Goodbye');
* }),
* },
* });
* ```
*
* @see https://github.com/chimurai/http-proxy-middleware/
* @see https://github.com/chimurai/http-proxy-middleware/#basic-usage
* @see https://github.com/chimurai/http-proxy-middleware/#intercept-and-manipulate-responses
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md
*/
export declare function createProxyMiddleware<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse, TNext = NextFunction>(options: Options<TReq, TRes>): RequestHandler<TReq, TRes, TNext>;
+81
View File
@@ -0,0 +1,81 @@
import { HttpProxyMiddleware } from './http-proxy-middleware.js';
/**
* Create proxy middleware for Express-like servers. ([list of servers with examples](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md))
*
* @example Basic proxy to a single target.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* changeOrigin: true,
* });
* ```
*
* @example Proxy only matching paths and rewrite the forwarded path.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://localhost:3000',
* pathFilter: '/api',
* pathRewrite: {
* '^/api/': '/',
* },
* });
* ```
*
* @example Native path rewrite by mounting at a route (alternative to `pathRewrite`).
* ```ts
* import express from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const app = express();
* app.use(
* '/users',
* createProxyMiddleware({
* target: 'http://jsonplaceholder.typicode.com/users',
* changeOrigin: true,
* }),
* );
* ```
*
* @example Use framework-specific request/response types (Express).
* ```ts
* import type { Request, Response } from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware<Request, Response>({
* target: 'http://www.example.org/api',
* changeOrigin: true,
* });
* ```
*
* @example Intercept and modify a proxied response body.
* ```ts
* import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* selfHandleResponse: true,
* on: {
* proxyRes: responseInterceptor(async (responseBuffer) => {
* const response = responseBuffer.toString('utf8');
* return response.replace('Hello', 'Goodbye');
* }),
* },
* });
* ```
*
* @see https://github.com/chimurai/http-proxy-middleware/
* @see https://github.com/chimurai/http-proxy-middleware/#basic-usage
* @see https://github.com/chimurai/http-proxy-middleware/#intercept-and-manipulate-responses
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md
*/
export function createProxyMiddleware(options) {
const { middleware } = new HttpProxyMiddleware(options);
return middleware;
}
+3
View File
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Options, Plugin } from './types.js';
export declare function getPlugins<TReq extends http.IncomingMessage, TRes extends http.ServerResponse>(options: Options<TReq, TRes>): Plugin<TReq, TRes>[];
+10
View File
@@ -0,0 +1,10 @@
import { debugProxyErrorsPlugin, errorResponsePlugin, loggerPlugin, proxyEventsPlugin, } from './plugins/default/index.js';
export function getPlugins(options) {
// don't load default errorResponsePlugin if user has specified their own
const maybeErrorResponsePlugin = options.on?.error ? [] : [errorResponsePlugin];
const defaultPlugins = options.ejectPlugins
? [] // no default plugins when ejecting
: [debugProxyErrorsPlugin, proxyEventsPlugin, loggerPlugin, ...maybeErrorResponsePlugin];
const userPlugins = options.plugins ?? [];
return [...defaultPlugins, ...userPlugins];
}
@@ -0,0 +1,12 @@
/**
* HPM_ERR_INVALID_MULTIPART prefixed error code will be used in
* [status-code.ts]({@link ../../status-code.ts}) to return status code 400.
*/
export declare const HPM_ERR_INVALID_MULTIPART = "HPM_ERR_INVALID_MULTIPART";
/**
* stringify FormData data
* @param contentType
* @param data
* @returns
*/
export declare function stringifyFormData(contentType: string, data: object): string;
@@ -0,0 +1,46 @@
import { HttpProxyMiddlewareError } from '../../errors.js';
const CR_OR_LF = /[\r\n]/;
/**
* HPM_ERR_INVALID_MULTIPART prefixed error code will be used in
* [status-code.ts]({@link ../../status-code.ts}) to return status code 400.
*/
export const HPM_ERR_INVALID_MULTIPART = 'HPM_ERR_INVALID_MULTIPART';
/**
* stringify FormData data
* @param contentType
* @param data
* @returns
*/
export function stringifyFormData(contentType, data) {
const boundary = getMultipartBoundary(contentType);
let str = '';
for (const [key, value] of Object.entries(data)) {
const normalizedKey = String(key);
const normalizedValue = String(value);
// Reject potentially dangerous sequences to prevent multipart header/body injection.
validateMultipartField(normalizedKey, normalizedValue, boundary);
str += `--${boundary}\r\nContent-Disposition: form-data; name="${escapeMultipartFieldName(normalizedKey)}"\r\n\r\n${normalizedValue}\r\n`;
}
return str;
}
function getMultipartBoundary(contentType) {
const boundaryMatch = /(?:^|;)\s*boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
// Keep backward-compatible behavior when boundary is omitted: fall back to legacy extraction.
const boundary = (boundaryMatch?.[1] ?? boundaryMatch?.[2] ?? contentType).trim();
if (!boundary || CR_OR_LF.test(boundary)) {
throw new HttpProxyMiddlewareError('[HPM] invalid multipart boundary detected.', `${HPM_ERR_INVALID_MULTIPART}_BOUNDARY`);
}
return boundary;
}
function validateMultipartField(fieldName, fieldValue, boundary) {
const boundaryDelimiter = `--${boundary}`;
if (CR_OR_LF.test(fieldName)) {
throw new HttpProxyMiddlewareError(`[HPM] invalid multipart field name "${fieldName}" detected.`, `${HPM_ERR_INVALID_MULTIPART}_FIELD_NAME`);
}
if (CR_OR_LF.test(fieldValue) || fieldValue.includes(boundaryDelimiter)) {
throw new HttpProxyMiddlewareError(`[HPM] invalid multipart field value for "${fieldName}" detected.`, `${HPM_ERR_INVALID_MULTIPART}_FIELD_VALUE`);
}
}
function escapeMultipartFieldName(fieldName) {
return fieldName.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
+22
View File
@@ -0,0 +1,22 @@
import type * as http from 'node:http';
export type BodyParserLikeRequest = http.IncomingMessage & {
body?: any;
};
/**
* Fix proxied body if bodyParser is involved.
*
* @example
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* on: {
* proxyReq: fixRequestBody,
* }
* });
* ```
*
* Alternative solution without using `fixRequestBody()`: put `http-proxy-middleware` before `bodyParser` in the middleware stack.
*
* @see {@link https://github.com/chimurai/http-proxy-middleware/issues/40 Github issue #40 - POST request body is not proxied}
*/
export declare function fixRequestBody<TReq extends BodyParserLikeRequest = BodyParserLikeRequest>(proxyReq: http.ClientRequest, req: TReq): void;
+78
View File
@@ -0,0 +1,78 @@
import * as querystring from 'node:querystring';
import * as zlib from 'node:zlib';
import { stringifyFormData } from './fix-request-body-utils/stringify-form-data.js';
/**
* Fix proxied body if bodyParser is involved.
*
* @example
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* on: {
* proxyReq: fixRequestBody,
* }
* });
* ```
*
* Alternative solution without using `fixRequestBody()`: put `http-proxy-middleware` before `bodyParser` in the middleware stack.
*
* @see {@link https://github.com/chimurai/http-proxy-middleware/issues/40 Github issue #40 - POST request body is not proxied}
*/
export function fixRequestBody(proxyReq, req) {
// skip fixRequestBody() when req.readableLength not 0 (bodyParser failure)
if (req.readableLength !== 0) {
return;
}
const requestBody = req.body;
if (!requestBody) {
return;
}
const contentType = proxyReq.getHeader('Content-Type');
if (!contentType) {
return;
}
const writeBody = (bodyData) => {
let proxyData = bodyData;
const contentEncoding = String(proxyReq.getHeader('Content-Encoding')).toLowerCase();
switch (contentEncoding) {
case 'br':
proxyData = zlib.brotliCompressSync(proxyData);
break;
case 'deflate':
proxyData = zlib.deflateSync(proxyData);
break;
case 'gzip':
proxyData = zlib.gzipSync(proxyData);
break;
case 'zstd':
proxyData = zlib.zstdCompressSync(proxyData);
break;
}
proxyReq.setHeader('Content-Length', Buffer.byteLength(proxyData));
proxyReq.write(proxyData);
};
try {
// Use if-elseif to prevent multiple writeBody/setHeader calls:
// Error: "Cannot set headers after they are sent to the client"
if (contentType.includes('application/json') || contentType.includes('+json')) {
writeBody(JSON.stringify(requestBody));
}
else if (contentType.includes('application/x-www-form-urlencoded')) {
writeBody(querystring.stringify(requestBody));
}
else if (contentType.includes('multipart/form-data')) {
writeBody(stringifyFormData(contentType, requestBody));
}
else if (contentType.includes('text/plain')) {
writeBody(requestBody);
}
}
catch (error) {
// proxyReq listeners run outside the middleware try/catch path; re-throwing here can bubble as
// an unhandled exception in consumers, so destroy() is used to fail closed through proxy error handling.
proxyReq.destroy(toError(error));
}
}
function toError(error) {
return error instanceof Error ? error : new Error(String(error));
}
+1
View File
@@ -0,0 +1 @@
export * from './public.js';
+1
View File
@@ -0,0 +1 @@
export * from './public.js';
+2
View File
@@ -0,0 +1,2 @@
export { responseInterceptor } from './response-interceptor.js';
export { fixRequestBody } from './fix-request-body.js';
+2
View File
@@ -0,0 +1,2 @@
export { responseInterceptor } from './response-interceptor.js';
export { fixRequestBody } from './fix-request-body.js';
@@ -0,0 +1,27 @@
import type * as http from 'node:http';
type Interceptor<TReq = http.IncomingMessage, TRes = http.ServerResponse> = (buffer: Buffer, proxyRes: http.IncomingMessage, req: TReq, res: TRes) => Promise<Buffer | string>;
/**
* Intercept responses from upstream.
* Automatically decompress (deflate, gzip, brotli, zstd).
* Give developer the opportunity to modify intercepted Buffer and http.ServerResponse
*
* NOTE: must set options.selfHandleResponse=true (prevent automatic call of res.end())
*
* @example
*
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* selfHandleResponse: true, // MUST set selfHandleResponse=true
* on: {
* proxyRes: responseInterceptor(async (buffer, proxyRes, req, res) => {
* // modify intercepted buffer and return modified buffer
* const modifiedBuffer = Buffer.from(buffer.toString().replace(/Example/g, 'Demo'), 'utf8');
* return modifiedBuffer;
* }),
* }
* });
* ```
*/
export declare function responseInterceptor<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(interceptor: Interceptor<TReq, TRes>): (proxyRes: http.IncomingMessage, req: TReq, res: TRes) => Promise<void>;
export {};
@@ -0,0 +1,145 @@
import * as zlib from 'node:zlib';
import { Debug } from '../debug.js';
import { getFunctionName } from '../utils/function.js';
const debug = Debug.extend('response-interceptor');
/**
* Intercept responses from upstream.
* Automatically decompress (deflate, gzip, brotli, zstd).
* Give developer the opportunity to modify intercepted Buffer and http.ServerResponse
*
* NOTE: must set options.selfHandleResponse=true (prevent automatic call of res.end())
*
* @example
*
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* selfHandleResponse: true, // MUST set selfHandleResponse=true
* on: {
* proxyRes: responseInterceptor(async (buffer, proxyRes, req, res) => {
* // modify intercepted buffer and return modified buffer
* const modifiedBuffer = Buffer.from(buffer.toString().replace(/Example/g, 'Demo'), 'utf8');
* return modifiedBuffer;
* }),
* }
* });
* ```
*/
export function responseInterceptor(interceptor) {
return async function proxyResResponseInterceptor(proxyRes, req, res) {
debug('intercept proxy response');
const originalProxyRes = proxyRes;
const chunks = [];
let bufferLength = 0;
// Bodyless responses (HEAD, 1xx, 204, 304) must not be decompressed.
const contentEncoding = isBodylessResponse(proxyRes.statusCode, req.method)
? undefined
: proxyRes.headers['content-encoding'];
// decompress proxy response
const _proxyRes = decompress(proxyRes, contentEncoding);
// collect data chunks and concatenate once on end to avoid repeated full-buffer copies
_proxyRes.on('data', (chunk) => {
const chunkBuffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
chunks.push(chunkBuffer);
bufferLength += chunkBuffer.length; // precalculate Buffer length for slightly better performance on Buffer.concat()
});
_proxyRes.on('end', async () => {
const buffer = Buffer.concat(chunks, bufferLength);
chunks.length = 0; // clear chunks array
bufferLength = 0;
// copy original headers
copyHeaders(proxyRes, res);
// RFC 9110: HEAD and 1xx/204/304 responses do not include content.
// End the response after headers to avoid writing an invalid body.
if (isBodylessResponse(proxyRes.statusCode, req.method)) {
res.end();
return;
}
// call interceptor with intercepted response (buffer)
debug('call interceptor function: %s', getFunctionName(interceptor));
const interceptedBuffer = Buffer.from(await interceptor(buffer, originalProxyRes, req, res));
// set correct content-length (with double byte character support)
debug('set content-length: %s', Buffer.byteLength(interceptedBuffer));
// Buffered responses cannot preserve trailer framing.
// Remove trailer declaration (and transfer-encoding just in case) before setting content-length.
res.removeHeader('trailer');
res.removeHeader('transfer-encoding');
res.setHeader('content-length', Buffer.byteLength(interceptedBuffer));
debug('write intercepted response');
res.write(interceptedBuffer);
res.end();
});
_proxyRes.on('error', (error) => {
chunks.length = 0; // clear chunks array
bufferLength = 0;
res.end(`Error fetching proxied request: ${error.message}`);
});
};
}
function isBodylessResponse(statusCode, method) {
return (method?.toUpperCase() === 'HEAD' ||
(statusCode !== undefined &&
((statusCode >= 100 && statusCode < 200) || statusCode === 204 || statusCode === 304)));
}
/**
* Streaming decompression of proxy response
* source: https://github.com/apache/superset/blob/9773aba522e957ed9423045ca153219638a85d2f/superset-frontend/webpack.proxy-config.js#L116
*/
function decompress(proxyRes, contentEncoding) {
let _proxyRes = proxyRes;
let decompress;
switch (contentEncoding) {
case 'gzip':
decompress = zlib.createGunzip();
break;
case 'br':
decompress = zlib.createBrotliDecompress();
break;
case 'deflate':
decompress = zlib.createInflate();
break;
case 'zstd':
decompress = zlib.createZstdDecompress();
break;
default:
break;
}
if (decompress) {
debug(`decompress proxy response with 'content-encoding': %s`, contentEncoding);
_proxyRes.pipe(decompress);
_proxyRes = decompress;
}
return _proxyRes;
}
/**
* Copy original headers
* https://github.com/apache/superset/blob/9773aba522e957ed9423045ca153219638a85d2f/superset-frontend/webpack.proxy-config.js#L78
*/
function copyHeaders(originalResponse, response) {
debug('copy original response headers');
if (originalResponse.statusCode) {
response.statusCode = originalResponse.statusCode;
}
if (originalResponse.statusMessage) {
response.statusMessage = originalResponse.statusMessage;
}
if (response.setHeader) {
let keys = Object.keys(originalResponse.headers);
// ignore encoding/framing headers that are incompatible with buffered interception
keys = keys.filter((key) => !['content-encoding', 'transfer-encoding', 'trailer'].includes(key));
keys.forEach((key) => {
let value = originalResponse.headers[key];
if (key === 'set-cookie' && value) {
// remove cookie domain
value = Array.isArray(value) ? value : [value];
value = value.map((x) => x.replace(/Domain=[^;]+?/i, ''));
}
response.setHeader(key, value);
});
}
else {
if ('headers' in response) {
response.headers = originalResponse.headers;
}
}
}
+31
View File
@@ -0,0 +1,31 @@
import type * as http from 'node:http';
import type { Options, RequestHandler } from './types.js';
export declare class HttpProxyMiddleware<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> {
#private;
private wsInternalSubscribedServers;
private activeServers;
private proxyOptions;
private proxy;
private pathRewriter;
private logger;
constructor(options: Options<TReq, TRes>);
middleware: RequestHandler<TReq, TRes>;
private registerPlugins;
private catchUpgradeRequest;
private handleUpgrade;
/**
* Determine whether request should be proxied.
*/
private shouldProxy;
/**
* Apply option.router and option.pathRewrite
* Order matters:
* Router uses original path for routing;
* NOT the modified path, after it has been rewritten by pathRewrite
* @param {Object} req
* @return {Object} proxy options
*/
private prepareProxyRequest;
private applyRouter;
private applyPathRewrite;
}
+183
View File
@@ -0,0 +1,183 @@
import { createProxyServer } from 'httpxy';
import { verifyConfig } from './configuration.js';
import { Debug as debug } from './debug.js';
import { getPlugins } from './get-plugins.js';
import { getLogger } from './logger.js';
import { matchPathFilter } from './path-filter.js';
import { createPathRewriter } from './path-rewriter.js';
import { getTarget } from './router.js';
import { getFunctionName } from './utils/function.js';
import { normalizeIPv6LiteralTargets } from './utils/ipv6.js';
export class HttpProxyMiddleware {
wsInternalSubscribedServers = new WeakSet();
activeServers = new Set();
proxyOptions;
proxy;
pathRewriter;
logger;
constructor(options) {
verifyConfig(options);
this.proxyOptions = options;
this.logger = getLogger(options);
debug(`create proxy server`);
this.proxy = createProxyServer({});
this.registerPlugins(this.proxy, this.proxyOptions);
this.pathRewriter = createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided
// https://github.com/chimurai/http-proxy-middleware/issues/19
// expose function to upgrade externally
this.middleware.upgrade = (req, socket, head) => {
const server = this.#getServer(req);
if (server && !this.wsInternalSubscribedServers.has(server)) {
this.handleUpgrade(req, socket, head);
}
};
}
#getServer(req) {
return req.socket?.server;
}
// https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this
middleware = (async (req, res, next) => {
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
let activeProxyOptions;
try {
// Preparation Phase: Apply router and path rewriter.
activeProxyOptions = await this.prepareProxyRequest(req, res);
// [Smoking Gun] httpxy is inconsistent with error handling:
// 1. If target is missing (here), it emits 'error' but returns a boolean (bypassing our catch/next).
// 2. If a network error occurs (in proxy.web), it rejects the promise but SKIPS emitting 'error'.
// We manually throw here to force Case 1 into the catch block so next(err) is called for Express.
if (!activeProxyOptions.target && !activeProxyOptions.forward) {
throw new Error('Must provide a proper URL as target');
}
}
catch (err) {
next?.(err);
return;
}
try {
// Proxying Phase: Handle the actual web request.
debug(`proxy request to target: %O`, activeProxyOptions.target);
await this.proxy.web(req, res, activeProxyOptions);
}
catch (err) {
// Manually emit 'error' event because httpxy's promise-based API does not emit it automatically.
// This is crucial for backward compatibility with HPM plugins (like error-response-plugin)
// and custom listeners registered via the 'on: { error: ... }' option.
this.proxy.emit('error', err, req, res, activeProxyOptions.target);
next?.(err);
}
}
else {
next?.();
}
/**
* Get the server object to subscribe to server events;
* 'upgrade' for websocket and 'close' for graceful shutdown
*/
const server = this.#getServer(req);
if (server && !this.activeServers.has(server)) {
debug('registering server close listener');
this.activeServers.add(server);
server.on('close', () => {
debug('server close signal received.');
this.activeServers.delete(server);
if (this.activeServers.size > 0) {
debug(`proxy server not closed: ${this.activeServers.size} server(s) still active`);
return;
}
else {
debug('closing proxy server');
this.proxy.close(() => debug('proxy server closed'));
}
});
}
if (this.proxyOptions.ws === true && server) {
// use initial request to access the server object to subscribe to http upgrade event
this.catchUpgradeRequest(server);
}
});
registerPlugins(proxy, options) {
const plugins = getPlugins(options);
plugins.forEach((plugin) => {
debug(`register plugin: "${getFunctionName(plugin)}"`);
plugin(proxy, options);
});
}
catchUpgradeRequest = (server) => {
if (!this.wsInternalSubscribedServers.has(server)) {
debug('subscribing to server upgrade event');
server.on('upgrade', this.handleUpgrade);
this.wsInternalSubscribedServers.add(server);
}
};
handleUpgrade = async (req, socket, head) => {
try {
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
// No HTTP response object exists during WebSocket upgrades, so pass undefined.
const activeProxyOptions = await this.prepareProxyRequest(req, undefined);
await this.proxy.ws(req, socket, activeProxyOptions, head);
debug('server upgrade event received. Proxying WebSocket');
}
}
catch (err) {
// This error does not include the URL as the fourth argument as we won't
// have the URL if `this.prepareProxyRequest` throws an error.
this.proxy.emit('error', err, req, socket);
}
};
/**
* Determine whether request should be proxied.
*/
shouldProxy = (pathFilter, req) => {
try {
return matchPathFilter(pathFilter, req.url, req);
}
catch (err) {
debug('Error: matchPathFilter() called with request url: ', `"${req.url}"`);
this.logger.error(err);
return false;
}
};
/**
* Apply option.router and option.pathRewrite
* Order matters:
* Router uses original path for routing;
* NOT the modified path, after it has been rewritten by pathRewrite
* @param {Object} req
* @return {Object} proxy options
*/
prepareProxyRequest = async (req, res) => {
const newProxyOptions = Object.assign({}, this.proxyOptions);
// Apply in order:
// 1. option.router
// 2. option.pathRewrite
await this.applyRouter(req, res, newProxyOptions);
normalizeIPv6LiteralTargets(newProxyOptions);
await this.applyPathRewrite(req, res, this.pathRewriter, newProxyOptions);
return newProxyOptions;
};
// Modify option.target when router present.
applyRouter = async (req, res, options) => {
let newTarget;
if (options.router) {
newTarget = await getTarget(req, res, options);
if (newTarget) {
debug('router new target: "%s"', newTarget);
options.target = newTarget;
}
}
};
// rewrite path
applyPathRewrite = async (req, res, pathRewriter, options) => {
if (req.url && pathRewriter) {
const path = await pathRewriter(req.url, req, res, options);
if (typeof path === 'string') {
debug('pathRewrite new path: %s', path);
req.url = path;
}
else {
debug('pathRewrite: no rewritten path found: %s', req.url);
}
}
};
}
+10
View File
@@ -0,0 +1,10 @@
/**
* Hono-specific API entrypoint.
*
* This is intentionally published as a dedicated subpath (`http-proxy-middleware/hono`)
* so the root package types do not import `hono` / `@hono/node-server`.
*
* Keeping these exports out of the root entrypoint prevents non-Hono consumers from
* getting TypeScript module-resolution errors for optional Hono dependencies.
*/
export { createHonoProxyMiddleware } from './factory-hono.js';
+10
View File
@@ -0,0 +1,10 @@
/**
* Hono-specific API entrypoint.
*
* This is intentionally published as a dedicated subpath (`http-proxy-middleware/hono`)
* so the root package types do not import `hono` / `@hono/node-server`.
*
* Keeping these exports out of the root entrypoint prevents non-Hono consumers from
* getting TypeScript module-resolution errors for optional Hono dependencies.
*/
export { createHonoProxyMiddleware } from './factory-hono.js';
+4
View File
@@ -0,0 +1,4 @@
export * from './factory.js';
export * from './handlers/index.js';
export type { Plugin, Filter, Options, RequestHandler, OnProxyEvent } from './types.js';
export * from './plugins/index.js';
+3
View File
@@ -0,0 +1,3 @@
export * from './factory.js';
export * from './handlers/index.js';
export * from './plugins/index.js';
+2
View File
@@ -0,0 +1,2 @@
import type { Logger, Options } from './types.js';
export declare function getLogger(options: Options): Logger;
+21
View File
@@ -0,0 +1,21 @@
/**
* Compatibility matrix
*
| Library | log | info | warn | error | \<interpolation\> |
|----------|:------|:-------|:------|:--------|:------------------|
| console | ✅ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
| bunyan | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
| pino | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
| winston | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O)^1 |
| log4js | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
*
* ^1: https://github.com/winstonjs/winston#string-interpolation
*/
const noopLogger = {
info: () => { },
warn: () => { },
error: () => { },
};
export function getLogger(options) {
return options.logger || noopLogger;
}
+3
View File
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Filter } from './types.js';
export declare function matchPathFilter<TReq extends http.IncomingMessage = http.IncomingMessage>(pathFilter: Filter<TReq> | undefined, uri: string | undefined, req: http.IncomingMessage): boolean;
+76
View File
@@ -0,0 +1,76 @@
import isGlob from 'is-glob';
import micromatch from 'micromatch';
import { HttpProxyMiddlewareError } from './errors.js';
export function matchPathFilter(pathFilter = '/', uri, req) {
// single path
if (isStringPath(pathFilter)) {
return matchSingleStringPath(pathFilter, uri);
}
// single glob path
if (isGlobPath(pathFilter)) {
return matchSingleGlobPath(pathFilter, uri);
}
// multi path
if (Array.isArray(pathFilter)) {
if (pathFilter.every(isStringPath)) {
return matchMultiPath(pathFilter, uri);
}
if (pathFilter.every(isGlobPath)) {
return matchMultiGlobPath(pathFilter, uri);
}
throw new HttpProxyMiddlewareError('[HPM] Invalid pathFilter. Plain paths (e.g. "/api") can not be mixed with globs (e.g. "/api/**"). Expecting something like: ["/api", "/ajax"] or ["/api/**", "!**.html"].', 'HPM_INVALID_PATH_FILTER_ARRAY_CONFIG');
}
// custom matching
if (typeof pathFilter === 'function') {
const pathname = getUrlPathName(uri);
return Boolean(pathFilter(pathname, req));
}
throw new HttpProxyMiddlewareError('[HPM] Invalid pathFilter. Expecting something like: "/api" or ["/api", "/ajax"]', 'HPM_INVALID_PATH_FILTER_CONFIG');
}
/**
* @param {String} pathFilter '/api'
* @param {String} uri 'http://example.org/api/b/c/d.html'
* @return {Boolean}
*/
function matchSingleStringPath(pathFilter, uri) {
const pathname = getUrlPathName(uri);
return pathname?.indexOf(pathFilter) === 0;
}
function matchSingleGlobPath(pattern, uri) {
const pathname = getUrlPathName(uri);
const matches = micromatch([pathname], pattern);
return matches && matches.length > 0;
}
function matchMultiGlobPath(patternList, uri) {
return matchSingleGlobPath(patternList, uri);
}
/**
* @param {String} pathFilterList ['/api', '/ajax']
* @param {String} uri 'http://example.org/api/b/c/d.html'
* @return {Boolean}
*/
function matchMultiPath(pathFilterList, uri) {
let isMultiPath = false;
for (const context of pathFilterList) {
if (matchSingleStringPath(context, uri)) {
isMultiPath = true;
break;
}
}
return isMultiPath;
}
/**
* Parses URI and returns RFC 3986 path
*
* @param {String} uri from req.url
* @return {String} RFC 3986 path
*/
function getUrlPathName(uri) {
return uri && new URL(uri, 'http://0.0.0.0').pathname;
}
function isStringPath(pathFilter) {
return typeof pathFilter === 'string' && !isGlob(pathFilter);
}
function isGlobPath(pathFilter) {
return isGlob(pathFilter);
}
+6
View File
@@ -0,0 +1,6 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { PathRewriteConfig } from './types.js';
/**
* Create rewrite function, to cache parsed rewrite rules.
*/
export declare function createPathRewriter<TReq extends IncomingMessage = IncomingMessage, TRes extends ServerResponse = ServerResponse>(rewriteConfig: PathRewriteConfig<TReq, TRes> | undefined): ((path: string, req: TReq, res?: TRes | undefined, options?: import("./types.js").Options<TReq, TRes> | undefined) => string | undefined) | ((path: string, req: TReq, res?: TRes | undefined, options?: import("./types.js").Options<TReq, TRes> | undefined) => Promise<string | undefined>) | undefined;
+59
View File
@@ -0,0 +1,59 @@
import isPlainObject from 'is-plain-obj';
import { Debug } from './debug.js';
import { HttpProxyMiddlewareError } from './errors.js';
const debug = Debug.extend('path-rewriter');
/**
* Create rewrite function, to cache parsed rewrite rules.
*/
export function createPathRewriter(rewriteConfig) {
let rulesCache;
if (!isValidRewriteConfig(rewriteConfig)) {
return;
}
if (typeof rewriteConfig === 'function') {
const customRewriteFn = rewriteConfig;
return customRewriteFn;
}
else {
rulesCache = parsePathRewriteRules(rewriteConfig);
return rewritePath;
}
function rewritePath(path) {
let result = path;
for (const rule of rulesCache) {
if (rule.regex.test(path)) {
result = result.replace(rule.regex, rule.value);
debug('rewriting path from "%s" to "%s"', path, result);
break;
}
}
return result;
}
}
function isValidRewriteConfig(rewriteConfig) {
if (typeof rewriteConfig === 'function') {
return true;
}
else if (isPlainObject(rewriteConfig)) {
return Object.keys(rewriteConfig).length !== 0;
}
else if (rewriteConfig === undefined || rewriteConfig === null) {
return false;
}
else {
throw new HttpProxyMiddlewareError('[HPM] Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function', 'HPM_INVALID_PATH_REWRITER_CONFIG');
}
}
function parsePathRewriteRules(rewriteConfig) {
const rules = [];
if (isPlainObject(rewriteConfig)) {
for (const [key, value] of Object.entries(rewriteConfig)) {
rules.push({
regex: new RegExp(key),
value: value,
});
debug('rewrite rule created: "%s" ~> "%s"', key, value);
}
}
return rules;
}
@@ -0,0 +1,6 @@
import type { Plugin } from '../../types.js';
/**
* Subscribe to {@link https://github.com/unjs/httpxy#events `httpxy` error events} to prevent server from crashing.
* Errors are logged with {@link https://www.npmjs.com/package/debug debug} library.
*/
export declare const debugProxyErrorsPlugin: Plugin;
@@ -0,0 +1,77 @@
import { styleText } from 'node:util';
import { Debug } from '../../debug.js';
import { definePlugin } from '../define-plugin.js';
const debug = Debug.extend('debug-proxy-errors-plugin');
const BODY_PARSER_ERROR_MESSAGE = `[HPM] Connection reset (ECONNRESET) detected with non-empty "req.body" [ERR_HPM.GH40].
This usually means that the POST request body (req.body) was already parsed before reaching the proxy.
When bodyParser runs first, it consumes the request stream, leaving the proxy unable to forward the body data to the target server.
How to fix this issue:
- Option 1: Place the proxy middleware before the bodyParser middleware.
- Option 2: Use 'fixRequestBody()' helper to fix this issue.
For more details, see: https://github.com/chimurai/http-proxy-middleware/issues/40\n`;
function hasParsedBody(req) {
return Boolean(req && req.method === 'POST' && 'body' in req && req.body);
}
/**
* Subscribe to {@link https://github.com/unjs/httpxy#events `httpxy` error events} to prevent server from crashing.
* Errors are logged with {@link https://www.npmjs.com/package/debug debug} library.
*/
export const debugProxyErrorsPlugin = definePlugin((proxyServer, options) => {
/**
* The old `http-proxy` doesn't handle any errors by default (https://github.com/http-party/node-http-proxy#listening-for-proxy-events)
* > We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.
* Subscribing to error event to prevent server from crashing
*/
proxyServer.on('error', (error, req, res, target) => {
debug(`httpxy error event: \n%O`, error);
// detect request body (when bodyParser used) and log an error message to help debugging
if (error.code === 'ECONNRESET' && hasParsedBody(req)) {
console.error(styleText('red', BODY_PARSER_ERROR_MESSAGE));
}
});
proxyServer.on('proxyReq', (proxyReq, req, socket) => {
socket.on('error', (error) => {
debug('Socket error in proxyReq event: \n%O', error);
});
});
/**
* Fix SSE close events
* @link https://github.com/chimurai/http-proxy-middleware/issues/678
* @link https://github.com/http-party/node-http-proxy/issues/1520#issue-877626125
*/
proxyServer.on('proxyRes', (proxyRes, req, res) => {
res.on('close', () => {
if (!res.writableEnded) {
debug('Destroying proxyRes in proxyRes close event');
proxyRes.destroy();
}
});
});
/**
* Fix crash when target server restarts
* https://github.com/chimurai/http-proxy-middleware/issues/476#issuecomment-746329030
* https://github.com/webpack/webpack-dev-server/issues/1642#issuecomment-790602225
*/
proxyServer.on('proxyReqWs', (proxyReq, req, socket) => {
socket.on('error', (error) => {
debug('Socket error in proxyReqWs event: \n%O', error);
});
});
proxyServer.on('open', (proxySocket) => {
proxySocket.on('error', (error) => {
debug('Socket error in open event: \n%O', error);
});
});
proxyServer.on('close', (req, socket, head) => {
socket.on('error', (error) => {
debug('Socket error in close event: \n%O', error);
});
});
// https://github.com/webpack/webpack-dev-server/issues/1642#issuecomment-1103136590
proxyServer.on('econnreset', (error, req, res, target) => {
debug(`httpxy econnreset event: \n%O`, error);
});
});
@@ -0,0 +1,2 @@
import type { Plugin } from '../../types.js';
export declare const errorResponsePlugin: Plugin;
@@ -0,0 +1,28 @@
import { getStatusCode } from '../../status-code.js';
import { sanitize } from '../../utils/sanitize.js';
import { definePlugin } from '../define-plugin.js';
function isResponseLike(obj) {
return obj && typeof obj.writeHead === 'function';
}
function isSocketLike(obj) {
return obj && typeof obj.write === 'function' && !('writeHead' in obj);
}
export const errorResponsePlugin = definePlugin((proxyServer, options) => {
proxyServer.on('error', (err, req, res, target) => {
// Re-throw error. Not recoverable since req & res are empty.
if (!req || !res) {
throw err; // "Error: Must provide a proper URL as target"
}
if (isResponseLike(res)) {
if (!res.headersSent) {
const statusCode = getStatusCode(err.code);
res.writeHead(statusCode);
}
const host = req.headers && req.headers.host;
res.end(`Error occurred while trying to proxy: ${sanitize(host)}${sanitize(req.url)}`);
}
else if (isSocketLike(res)) {
res.destroy();
}
});
});
+4
View File
@@ -0,0 +1,4 @@
export * from './debug-proxy-errors-plugin.js';
export * from './error-response-plugin.js';
export * from './logger-plugin.js';
export * from './proxy-events.js';
+4
View File
@@ -0,0 +1,4 @@
export * from './debug-proxy-errors-plugin.js';
export * from './error-response-plugin.js';
export * from './logger-plugin.js';
export * from './proxy-events.js';
@@ -0,0 +1,2 @@
import type { Plugin } from '../../types.js';
export declare const loggerPlugin: Plugin;
@@ -0,0 +1,57 @@
import { URL } from 'node:url';
import { getLogger } from '../../logger.js';
import { createUrl } from '../../utils/create-url.js';
import { getPort } from '../../utils/logger-plugin.js';
import { definePlugin } from '../define-plugin.js';
export const loggerPlugin = definePlugin((proxyServer, options) => {
const logger = getLogger(options);
proxyServer.on('error', (err, req, res, target) => {
const hostname = req?.headers?.host;
const requestHref = `${hostname}${req?.url}`;
const targetHref = `${target?.href}`; // target is undefined when websocket errors
const errorMessage = '[HPM] Error occurred while proxying request %s to %s [%s] (%s)';
const errReference = 'https://nodejs.org/api/errors.html#errors_common_system_errors'; // link to Node Common Systems Errors page
logger.error(errorMessage, requestHref, targetHref, err.code || err, errReference);
});
/**
* Log request and response
* @example
* ```shell
* [HPM] GET /users/ -> http://jsonplaceholder.typicode.com/users/ [304]
* ```
*/
proxyServer.on('proxyRes', (proxyRes, req, res) => {
// BrowserSync uses req.originalUrl
// Next.js doesn't have req.baseUrl
const originalUrl = req.originalUrl ?? `${req.baseUrl || ''}${req.url}`;
// construct targetUrl
let target;
try {
const port = getPort(proxyRes.req?.agent?.sockets);
const { protocol, host, path } = proxyRes.req;
target = createUrl({ protocol, host, port, path });
}
catch (err) {
// should not error. keeping fallback just in case
console.error('[HPM] Unexpected error while creating target URL', err);
// fallback to old implementation (less correct - without port)
target = new URL(options.target);
target.pathname = proxyRes.req.path;
}
const targetUrl = target.toString();
const exchange = `[HPM] ${req.method} ${originalUrl} -> ${targetUrl} [${proxyRes.statusCode}]`;
logger.info(exchange);
});
/**
* When client opens WebSocket connection
*/
proxyServer.on('open', (socket) => {
logger.info('[HPM] Client connected: %o', socket.address());
});
/**
* When client closes WebSocket connection
*/
proxyServer.on('close', (req, proxySocket, proxyHead) => {
logger.info('[HPM] Client disconnected: %o', proxySocket.address());
});
});
@@ -0,0 +1,22 @@
import type { Plugin } from '../../types.js';
/**
* Implements option.on object to subscribe to `httpxy` events.
*
* @example
* ```js
* createProxyMiddleware({
* on: {
* error: (error, req, res, target) => {},
* proxyReq: (proxyReq, req, res, options) => {},
* proxyReqWs: (proxyReq, req, socket, options) => {},
* proxyRes: (proxyRes, req, res) => {},
* open: (proxySocket) => {},
* close: (proxyRes, proxySocket, proxyHead) => {},
* start: (req, res, target) => {},
* end: (req, res, proxyRes) => {},
* econnreset: (error, req, res, target) => {},
* }
* });
* ```
*/
export declare const proxyEventsPlugin: Plugin;
@@ -0,0 +1,42 @@
import { Debug } from '../../debug.js';
import { getFunctionName } from '../../utils/function.js';
import { definePlugin } from '../define-plugin.js';
const debug = Debug.extend('proxy-events-plugin');
/**
* Implements option.on object to subscribe to `httpxy` events.
*
* @example
* ```js
* createProxyMiddleware({
* on: {
* error: (error, req, res, target) => {},
* proxyReq: (proxyReq, req, res, options) => {},
* proxyReqWs: (proxyReq, req, socket, options) => {},
* proxyRes: (proxyRes, req, res) => {},
* open: (proxySocket) => {},
* close: (proxyRes, proxySocket, proxyHead) => {},
* start: (req, res, target) => {},
* end: (req, res, proxyRes) => {},
* econnreset: (error, req, res, target) => {},
* }
* });
* ```
*/
export const proxyEventsPlugin = definePlugin((proxyServer, options) => {
if (!options.on) {
return;
}
// hoist variable here for better typing
let eventName;
// for in provide better typing than Object.entries()
for (eventName in options.on) {
if (Object.prototype.hasOwnProperty.call(options.on, eventName)) {
const handler = options.on[eventName];
if (!handler) {
continue;
}
debug(`register event handler: "${eventName}" -> "${getFunctionName(handler)}"`);
proxyServer.on(eventName, handler);
}
}
});
+25
View File
@@ -0,0 +1,25 @@
import type * as http from 'node:http';
import type { Plugin } from '../types.js';
/**
* Helper function to define a http-proxy-middleware plugin
* @see proxyServer {@link ProxyServer} - proxy server instance to which the plugin is being applied
* @see options {@link Options} - options object passed to `createProxyMiddleware`
*
* @example defining a plugin
* ```js
* export const myPlugin = definePlugin((proxyServer, options) => {
* // plugin implementation
* });
* ```
*
* @example using a plugin
* ```js
* createProxyMiddleware({
* target: 'http://example.com',
* plugins: [myPlugin],
* });
* ```
*
* @since 4.1.0
*/
export declare function definePlugin<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(fn: Plugin<TReq, TRes>): Plugin<TReq, TRes>;
+25
View File
@@ -0,0 +1,25 @@
/**
* Helper function to define a http-proxy-middleware plugin
* @see proxyServer {@link ProxyServer} - proxy server instance to which the plugin is being applied
* @see options {@link Options} - options object passed to `createProxyMiddleware`
*
* @example defining a plugin
* ```js
* export const myPlugin = definePlugin((proxyServer, options) => {
* // plugin implementation
* });
* ```
*
* @example using a plugin
* ```js
* createProxyMiddleware({
* target: 'http://example.com',
* plugins: [myPlugin],
* });
* ```
*
* @since 4.1.0
*/
export function definePlugin(fn) {
return fn;
}
+2
View File
@@ -0,0 +1,2 @@
export * from './define-plugin.js';
export * from './default/index.js';
+4
View File
@@ -0,0 +1,4 @@
// definePlugin()
export * from './define-plugin.js';
// default plugins
export * from './default/index.js';
+3
View File
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Options } from './index.js';
export declare function getTarget<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(req: TReq, res: TRes | undefined, config: Options<TReq, TRes>): Promise<import("httpxy").ProxyTarget | undefined>;
+60
View File
@@ -0,0 +1,60 @@
import isPlainObject from 'is-plain-obj';
import { Debug } from './debug.js';
const debug = Debug.extend('router');
export async function getTarget(req, res, config) {
let newTarget;
const router = config.router;
if (isPlainObject(router)) {
newTarget = getTargetFromProxyTable(req, router);
}
else if (typeof router === 'function') {
newTarget = await router(req, res, config);
}
return newTarget;
}
function getTargetFromProxyTable(req, table) {
let result;
const host = req.headers.host ?? '';
const path = req.url ?? '';
for (const [key, value] of Object.entries(table)) {
if (containsPath(key)) {
if (isHostAndPathKey(key)) {
const [keyHost, keyPath] = splitHostAndPathKey(key);
// SECURITY: host+path keys must match exact host + path prefix.
if (host === keyHost && path.startsWith(keyPath)) {
// match 'localhost:3000/api'
result = value;
debug('match: "%s" -> "%s"', key, result);
break;
}
}
else {
if (path.startsWith(key)) {
// match '/api'
result = value;
debug('match: "%s" -> "%s"', key, result);
break;
}
}
}
else {
if (key === host) {
// match 'localhost:3000'
result = value;
debug('match: "%s" -> "%s"', host, result);
break;
}
}
}
return result;
}
function containsPath(v) {
return v.indexOf('/') > -1;
}
function isHostAndPathKey(v) {
return containsPath(v) && !v.startsWith('/');
}
function splitHostAndPathKey(v) {
const firstSlash = v.indexOf('/');
return [v.slice(0, firstSlash), v.slice(firstSlash)];
}
+1
View File
@@ -0,0 +1 @@
export declare function getStatusCode(errorCode: string): number;
+23
View File
@@ -0,0 +1,23 @@
export function getStatusCode(errorCode) {
let statusCode;
if (/HPE_INVALID/.test(errorCode)) {
statusCode = 502;
return statusCode;
}
if (/HPM_ERR_INVALID_MULTIPART_/.test(errorCode)) {
statusCode = 400;
return statusCode;
}
switch (errorCode) {
case 'ECONNRESET':
case 'ENOTFOUND':
case 'ECONNREFUSED':
case 'ETIMEDOUT':
statusCode = 504;
break;
default:
statusCode = 500;
break;
}
return statusCode;
}
+139
View File
@@ -0,0 +1,139 @@
/**
* Based on definition by DefinitelyTyped:
* https://github.com/DefinitelyTyped/DefinitelyTyped/blob/6f529c6c67a447190f86bfbf894d1061e41e07b7/types/http-proxy-middleware/index.d.ts
*/
import type * as http from 'node:http';
import type * as net from 'node:net';
import type { ProxyServer, ProxyServerOptions } from 'httpxy';
export type NextFunction<T = (err?: any) => void> = T;
export interface RequestHandler<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse, TNext = NextFunction> {
(req: TReq, res: TRes, next?: TNext): Promise<void>;
upgrade: (req: TReq, socket: net.Socket, head: Buffer) => void;
}
export type Filter<TReq extends http.IncomingMessage = http.IncomingMessage> = string | string[] | ((pathname: string, req: TReq) => boolean | string | RegExpMatchArray | null);
/**
* @see {@link https://github.com/chimurai/http-proxy-middleware/tree/master#defineplugin-helper `definePlugin()`} to define a http-proxy-middleware plugin.
*/
export interface Plugin<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> {
(proxyServer: ProxyServer<TReq, TRes>, options: Options<TReq, TRes>): void;
}
export interface OnProxyEvent<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> {
error?: (err: Error, req: TReq, res: TRes | net.Socket, target?: string | Partial<URL>) => void;
proxyReq?: (proxyReq: http.ClientRequest, req: TReq, res: TRes, options: ProxyServerOptions) => void;
proxyReqWs?: (proxyReq: http.ClientRequest, req: TReq, socket: net.Socket, options: ProxyServerOptions, head: any) => void;
proxyRes?: (proxyRes: TReq, req: TReq, res: TRes) => void | Promise<void>;
open?: (proxySocket: net.Socket) => void;
close?: (proxyRes: TReq, proxySocket: net.Socket, proxyHead: any) => void;
start?: (req: TReq, res: TRes, target: string | Partial<URL>) => void;
end?: (req: TReq, res: TRes, proxyRes: TReq) => void;
econnreset?: (err: Error, req: TReq, res: TRes, target: string | Partial<URL>) => void;
}
export type Logger = Pick<Console, 'info' | 'warn' | 'error'>;
export type PathRewriteConfig<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> = {
[regexp: string]: string;
} | ((path: string, req: TReq,
/** `res` is undefined in WebSocket upgrade flows. */
res?: TRes | undefined, options?: Options<TReq, TRes>) => string | undefined) | ((path: string, req: TReq,
/** `res` is undefined in WebSocket upgrade flows. */
res?: TRes | undefined, options?: Options<TReq, TRes>) => Promise<string | undefined>);
export interface Options<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> extends ProxyServerOptions {
/**
* Narrow down requests to proxy or not.
* Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server.
* Or use the {@link http.IncomingMessage `req`} object for more complex filtering.
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md
* @since v3.0.0
*/
pathFilter?: Filter<TReq>;
/**
* Modify request paths before requests are send to the target.
* @example
* ```js
* createProxyMiddleware({
* pathRewrite: {
* '^/api/old-path': '/api/new-path', // rewrite path
* }
* });
* ```
* @since v0.15.0
* @since v0.21.0 - support `async` function
* @since v4.1.0 - `res` and `options` parameters added to custom function
*
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md
*/
pathRewrite?: PathRewriteConfig<TReq, TRes>;
/**
* Access the internal `httpxy` server instance to customize behavior
*
* @example
* ```js
* createProxyMiddleware({
* plugins: [(proxyServer, options) => {
* proxyServer.on('error', (error, req, res) => {
* console.error(error);
* });
* }]
* });
* ```
* @link https://github.com/chimurai/http-proxy-middleware#plugins-array
* @since v3.0.0
*/
plugins?: Plugin<TReq, TRes>[];
/**
* Eject pre-configured plugins.
* NOTE: register your own error handlers to prevent server from crashing.
*
* @link https://github.com/chimurai/http-proxy-middleware#ejectplugins-boolean-default-false
* @since v3.0.0
*/
ejectPlugins?: boolean;
/**
* Listen to `httpxy` events
* @see {@link OnProxyEvent} for available events
* @example
* ```js
* createProxyMiddleware({
* on: {
* error: (error, req, res, target) => {
* console.error(error);
* }
* }
* });
* ```
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/proxy-events.md
* @since v3.0.0
*/
on?: OnProxyEvent<TReq, TRes>;
/**
* Dynamically set the {@link Options.target `options.target`}.
*
* @example
* ```js
* createProxyMiddleware({
* router: async (req, res, options) => {
* return 'http://127:0.0.1:3000';
* }
* });
* ```
*
* @since v0.16.0
* @since v4.1.0 - `res` and `options` parameters added to router function signature
*
* NOTE: `res` is undefined in WebSocket upgrade flows.
*
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/router.md
*/
router?: Record<string, ProxyServerOptions['target']> | ((req: TReq, res: TRes | undefined, options: Options<TReq, TRes>) => ProxyServerOptions['target']) | ((req: TReq, res: TRes | undefined, options: Options<TReq, TRes>) => Promise<ProxyServerOptions['target']>);
/**
* Log information from http-proxy-middleware
* @example
* ```js
* createProxyMiddleware({
* logger: console
* });
* ```
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md
* @since v3.0.0
*/
logger?: Logger;
}
+1
View File
@@ -0,0 +1 @@
export {};
+9
View File
@@ -0,0 +1,9 @@
import { URL } from 'url';
type CreateUrlParams = {
protocol?: string;
host?: string;
port?: string;
path?: string;
};
export declare function createUrl({ protocol, host, port, path }: CreateUrlParams): URL;
export {};
+17
View File
@@ -0,0 +1,17 @@
import { URL } from 'url';
export function createUrl({ protocol, host, port, path }) {
// wrap IPv6 host in brackets
const ipv6Host = host?.includes(':') ? `[${host}]` : host;
// use fallback values to create a valid URL (protocol: 'undefined:', host: '[::]')
// nock v13 issue: protocol and host are undefined (https://github.com/chimurai/http-proxy-middleware/issues/1035)
// nock v14+ seems to return protocol and host correctly
const base = `${protocol || 'undefined:'}//${ipv6Host || '[::]'}`;
const url = new URL(base);
if (port) {
url.port = port;
}
if (path) {
url.pathname = path;
}
return url;
}
+1
View File
@@ -0,0 +1 @@
export declare function getFunctionName(fn: Function): string;
+4
View File
@@ -0,0 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-function-type */
export function getFunctionName(fn) {
return fn.name || '[anonymous Function]';
}
+20
View File
@@ -0,0 +1,20 @@
import type * as http from 'node:http';
import type { Options } from '../types.js';
/**
* Normalize bracketed IPv6 URL targets into unbracketed host options.
*
* RFC 2732 defines the URL syntax for literal IPv6 addresses as bracketed
* host references (for example `http://[::1]:8080/path` where host is
* `[::1]`).
*
* `httpxy` resolves bracketed hostnames (for example `[::1]`) via DNS,
* which can fail for IPv6 literals. This converts string/URL `target` and
* `forward` values into object form with `hostname: ::1` (brackets removed)
* so the address can be connected directly.
*
* Reference: RFC 2732, Section 2 (Literal IPv6 Address Format in URL's)
* https://www.ietf.org/rfc/rfc2732.txt
*
* The provided options object is mutated in place.
*/
export declare function normalizeIPv6LiteralTargets<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(options: Options<TReq, TRes>): void;
+66
View File
@@ -0,0 +1,66 @@
import { Debug } from '../debug.js';
const debug = Debug.extend('ipv6');
/**
* Normalize bracketed IPv6 URL targets into unbracketed host options.
*
* RFC 2732 defines the URL syntax for literal IPv6 addresses as bracketed
* host references (for example `http://[::1]:8080/path` where host is
* `[::1]`).
*
* `httpxy` resolves bracketed hostnames (for example `[::1]`) via DNS,
* which can fail for IPv6 literals. This converts string/URL `target` and
* `forward` values into object form with `hostname: ::1` (brackets removed)
* so the address can be connected directly.
*
* Reference: RFC 2732, Section 2 (Literal IPv6 Address Format in URL's)
* https://www.ietf.org/rfc/rfc2732.txt
*
* The provided options object is mutated in place.
*/
export function normalizeIPv6LiteralTargets(options) {
options.target = normalizeIPv6ProxyTarget(options.target, 'target');
options.forward = normalizeIPv6ProxyTarget(options.forward, 'forward');
}
function normalizeIPv6ProxyTarget(target, optionName) {
const targetUrl = toTargetUrl(target);
if (targetUrl && isBracketedIPv6Hostname(targetUrl.hostname)) {
const normalizedHostname = normalizeIPv6DestinationHostname(stripBrackets(targetUrl.hostname));
debug('normalized IPv6 "%s" %s', optionName, target);
const auth = targetUrl.username || targetUrl.password
? `${targetUrl.username}:${targetUrl.password}`
: undefined;
return {
hostname: normalizedHostname,
auth,
pathname: targetUrl.pathname,
port: targetUrl.port,
protocol: targetUrl.protocol,
search: targetUrl.search,
};
}
return target;
}
function toTargetUrl(target) {
if (typeof target === 'string') {
return new URL(target);
}
if (target instanceof URL) {
return target;
}
return undefined;
}
function isBracketedIPv6Hostname(hostname) {
return hostname.startsWith('[') && hostname.endsWith(']');
}
function stripBrackets(hostname) {
return hostname.replace(/^\[|\]$/g, '');
}
function normalizeIPv6DestinationHostname(hostname) {
// The unspecified address (::) is not a routable destination for outbound client requests.
// Treat it as loopback so a target like http://[::]:port reaches local IPv6 listeners.
if (hostname === '::') {
debug('normalizing hostname unspecified IPv6 address (::) to loopback (::1)');
return '::1';
}
return hostname;
}
+7
View File
@@ -0,0 +1,7 @@
import type { Agent } from 'node:http';
export type Sockets = Pick<Agent, 'sockets'>;
/**
* Get port from target
* Using proxyRes.req.agent.sockets to determine the target port
*/
export declare function getPort(sockets?: Sockets): string | undefined;
+7
View File
@@ -0,0 +1,7 @@
/**
* Get port from target
* Using proxyRes.req.agent.sockets to determine the target port
*/
export function getPort(sockets) {
return Object.keys(sockets || {})?.[0]?.split(':')[1];
}
+1
View File
@@ -0,0 +1 @@
export declare function sanitize(input: string | undefined): string;
+3
View File
@@ -0,0 +1,3 @@
export function sanitize(input) {
return input?.replace(/[<>]/g, (i) => encodeURIComponent(i)) ?? '';
}
+121
View File
@@ -0,0 +1,121 @@
{
"name": "http-proxy-middleware",
"version": "4.2.0",
"description": "The one-liner node.js proxy middleware for connect, express, next.js and more",
"keywords": [
"browser-sync",
"connect",
"cors",
"express",
"fastify",
"grunt-contrib-connect",
"gulp",
"hono",
"http",
"https",
"middleware",
"next.js",
"polka",
"proxy",
"reverse",
"websocket",
"ws"
],
"homepage": "https://github.com/chimurai/http-proxy-middleware#readme",
"bugs": {
"url": "https://github.com/chimurai/http-proxy-middleware/issues"
},
"license": "MIT",
"author": "Steven Chim",
"repository": {
"type": "git",
"url": "git+https://github.com/chimurai/http-proxy-middleware.git"
},
"files": [
"dist"
],
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"default": "./dist/index.js"
},
"./hono": {
"types": "./dist/index-hono.d.ts",
"import": "./dist/index-hono.js",
"default": "./dist/index-hono.js"
}
},
"publishConfig": {
"provenance": true
},
"scripts": {
"clean": "rm -rf dist coverage tsconfig.tsbuildinfo .eslintcache",
"install:all": "yarn && (cd examples && yarn)",
"lint": "yarn format && yarn eslint",
"lint:fix": "yarn format:fix && yarn eslint:fix",
"eslint": "eslint --cache '**/*.{js,ts,mjs,mts}'",
"eslint:fix": "yarn eslint --fix",
"format": "oxfmt --list-different \"**/*.{js,ts,mjs,mts,md,yml,json,html}\"",
"format:fix": "oxfmt --write \"**/*.{js,ts,mjs,mts,md,yml,json,html}\"",
"build": "tsc --build",
"test": "vitest run",
"test:types": "tsc --project tsconfig.test.json --noEmit",
"coverage": "vitest run --coverage",
"prepare": "husky",
"prepack": "yarn clean && yarn test && yarn build",
"spellcheck": "npx --yes cspell --show-context --show-suggestions '**/*.*'"
},
"dependencies": {
"debug": "^4.4.3",
"httpxy": "^0.5.4",
"is-glob": "^4.0.3",
"is-plain-obj": "^4.1.0",
"micromatch": "^4.0.8"
},
"devDependencies": {
"@commitlint/cli": "21.2.0",
"@commitlint/config-conventional": "21.2.0",
"@eslint/js": "10.0.1",
"@hono/node-server": "2.0.8",
"@types/debug": "4.1.13",
"@types/eslint": "9.6.1",
"@types/express": "5.0.6",
"@types/is-glob": "4.0.4",
"@types/micromatch": "4.0.10",
"@types/node": "26.1.0",
"@types/supertest": "7.2.0",
"@types/ws": "8.18.1",
"@vitest/coverage-v8": "4.1.9",
"body-parser": "2.3.0",
"eslint": "10.6.0",
"express": "5.2.1",
"get-port": "7.2.0",
"globals": "17.7.0",
"hono": "4.12.27",
"husky": "9.1.7",
"lint-staged": "17.0.8",
"mockttp": "4.4.2",
"msw": "2.14.6",
"nock": "14.0.16",
"open": "11.0.0",
"oxfmt": "0.57.0",
"pkg-pr-new": "0.0.75",
"supertest": "7.2.2",
"typescript": "6.0.3",
"typescript-eslint": "8.62.1",
"vitest": "4.1.9",
"ws": "8.21.0"
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"engines": {
"node": "^22.15.0 || ^24.0.0 || >=26.0.0"
}
}