Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"typicode",
"vhosted",
"websockets",
"xfwd"
"xfwd",
"httpxy"
]
}
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,8 @@
"ws": "8.19.0"
},
"dependencies": {
"@types/http-proxy": "^1.17.15",
"debug": "^4.3.6",
"http-proxy": "^1.18.1",
"httpxy": "^0.2.2",
Comment thread
chimurai marked this conversation as resolved.
"is-glob": "^4.0.3",
Comment thread
chimurai marked this conversation as resolved.
"is-plain-object": "^5.0.0",
"micromatch": "^4.0.8"
Expand Down
23 changes: 0 additions & 23 deletions patches/http-proxy+1.18.1.patch

This file was deleted.

6 changes: 3 additions & 3 deletions src/handlers/response-interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const debug = Debug.extend('response-interceptor');

type Interceptor<TReq = http.IncomingMessage, TRes = http.ServerResponse> = (
buffer: Buffer,
proxyRes: TReq,
proxyRes: http.IncomingMessage,
Comment thread
chimurai marked this conversation as resolved.
req: TReq,
res: TRes,
) => Promise<Buffer | string>;
Expand All @@ -25,7 +25,7 @@ export function responseInterceptor<
TRes extends http.ServerResponse = http.ServerResponse,
>(interceptor: Interceptor<TReq, TRes>) {
return async function proxyResResponseInterceptor(
proxyRes: TReq,
proxyRes: http.IncomingMessage,
req: TReq,
res: TRes,
): Promise<void> {
Expand All @@ -34,7 +34,7 @@ export function responseInterceptor<
let buffer = Buffer.from('', 'utf8');

// decompress proxy response
const _proxyRes = decompress<TReq>(proxyRes, proxyRes.headers['content-encoding']);
const _proxyRes = decompress(proxyRes, proxyRes.headers['content-encoding']);

// concat data stream
_proxyRes.on('data', (chunk) => (buffer = Buffer.concat([buffer, chunk])));
Expand Down
58 changes: 49 additions & 9 deletions src/http-proxy-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type * as http from 'node:http';
import type * as https from 'node:https';
import type * as net from 'node:net';

import * as httpProxy from 'http-proxy';
import { type ProxyServer, createProxyServer } from 'httpxy';

import { verifyConfig } from './configuration';
import { Debug as debug } from './debug';
Expand All @@ -18,7 +18,7 @@ export class HttpProxyMiddleware<TReq, TRes> {
private wsInternalSubscribed = false;
private serverOnCloseSubscribed = false;
private proxyOptions: Options<TReq, TRes>;
private proxy: httpProxy<TReq, TRes>;
private proxy: ProxyServer<TReq, TRes>;
private pathRewriter;
private logger: Logger;

Expand All @@ -28,7 +28,7 @@ export class HttpProxyMiddleware<TReq, TRes> {
this.logger = getLogger(options as unknown as Options);

debug(`create proxy server`);
this.proxy = httpProxy.createProxyServer({});
this.proxy = createProxyServer({});

this.registerPlugins(this.proxy, this.proxyOptions);

Expand All @@ -46,11 +46,41 @@ export class HttpProxyMiddleware<TReq, TRes> {
// https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this
public middleware: RequestHandler = (async (req, res, next?) => {
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
let activeProxyOptions: Options<TReq, TRes>;
try {
const activeProxyOptions = await this.prepareProxyRequest(req);
// Preparation Phase: Apply router and path rewriter.
activeProxyOptions = await this.prepareProxyRequest(req);

// [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);
this.proxy.web(req, res, activeProxyOptions);
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.

/**
* TODO: Ideally, TReq and TRes should be restricted via "TReq extends http.IncomingMessage = http.IncomingMessage"
* and "TRes extends http.ServerResponse = http.ServerResponse", which allows us to avoid the "req as TReq" below.
*
* However, making TReq and TRes constrained types may cause a breaking change for TypeScript users downstream.
* So we leave this as a TODO for now, and revisit it in a future major release.
*/
this.proxy.emit('error', err as Error, req as TReq, res, activeProxyOptions.target);

next?.(err);
}
} else {
Expand All @@ -70,7 +100,9 @@ export class HttpProxyMiddleware<TReq, TRes> {
if (server && !this.serverOnCloseSubscribed) {
server.on('close', () => {
debug('server close signal received: closing proxy server');
this.proxy.close();
this.proxy.close(() => {
debug('proxy server closed');
});
});
this.serverOnCloseSubscribed = true;
}
Expand All @@ -81,7 +113,7 @@ export class HttpProxyMiddleware<TReq, TRes> {
}
}) as RequestHandler;

private registerPlugins(proxy: httpProxy<TReq, TRes>, options: Options<TReq, TRes>) {
private registerPlugins(proxy: ProxyServer<TReq, TRes>, options: Options<TReq, TRes>) {
const plugins = getPlugins<TReq, TRes>(options);
plugins.forEach((plugin) => {
debug(`register plugin: "${getFunctionName(plugin)}"`);
Expand All @@ -103,13 +135,21 @@ export class HttpProxyMiddleware<TReq, TRes> {
try {
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
const activeProxyOptions = await this.prepareProxyRequest(req);
this.proxy.ws(req, socket, head, activeProxyOptions);
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);

/**
* TODO: Ideally, TReq and TRes should be restricted via "TReq extends http.IncomingMessage = http.IncomingMessage"
* and "TRes extends http.ServerResponse = http.ServerResponse", which allows us to avoid the "req as TReq" below.
*
* However, making TReq and TRes constrained types may cause a breaking change for TypeScript users downstream.
* So we leave this as a TODO for now, and revisit it in a future major release.
*/
this.proxy.emit('error', err as Error, req as TReq, socket);
}
};

Expand Down
2 changes: 1 addition & 1 deletion src/plugins/default/error-response-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function isSocketLike(obj: any): obj is Socket {
export const errorResponsePlugin: Plugin = (proxyServer, options) => {
proxyServer.on('error', (err, req, res, target?) => {
// Re-throw error. Not recoverable since req & res are empty.
if (!req && !res) {
if (!req || !res) {
throw err; // "Error: Must provide a proper URL as target"
}
Comment thread
chimurai marked this conversation as resolved.
Comment thread
chimurai marked this conversation as resolved.

Expand Down
21 changes: 17 additions & 4 deletions src/plugins/default/proxy-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,21 @@ const debug = Debug.extend('proxy-events-plugin');
* ```
*/
export const proxyEventsPlugin: Plugin = (proxyServer, options) => {
Object.entries(options.on || {}).forEach(([eventName, handler]) => {
debug(`register event handler: "${eventName}" -> "${getFunctionName(handler)}"`);
proxyServer.on(eventName, handler as (...args: unknown[]) => void);
});
if (!options.on) {
return;
}

// hoist variable here for better typing
let eventName: keyof typeof options.on;
// 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<keyof typeof options.on>(eventName, handler as (...args: unknown[]) => void);
}
}
};
45 changes: 29 additions & 16 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import type * as http from 'node:http';
import type * as net from 'node:net';

import type * as httpProxy from 'http-proxy';
import type { ProxyServer, ProxyServerOptions } from 'httpxy';

export type NextFunction<T = (err?: any) => void> = T;

Expand All @@ -24,25 +24,38 @@ export type Filter<TReq = http.IncomingMessage> =
| ((pathname: string, req: TReq) => boolean);

export interface Plugin<TReq = http.IncomingMessage, TRes = http.ServerResponse> {
(proxyServer: httpProxy<TReq, TRes>, options: Options<TReq, TRes>): void;
(proxyServer: ProxyServer<TReq, TRes>, options: Options<TReq, TRes>): void;
}

export interface OnProxyEvent<TReq = http.IncomingMessage, TRes = http.ServerResponse> {
error?: httpProxy.ErrorCallback<Error, TReq, TRes>;
proxyReq?: httpProxy.ProxyReqCallback<http.ClientRequest, TReq, TRes>;
proxyReqWs?: httpProxy.ProxyReqWsCallback<http.ClientRequest, TReq>;
proxyRes?: httpProxy.ProxyResCallback<TReq, TRes>;
open?: httpProxy.OpenCallback;
close?: httpProxy.CloseCallback<TReq>;
start?: httpProxy.StartCallback<TReq, TRes>;
end?: httpProxy.EndCallback<TReq, TRes>;
econnreset?: httpProxy.EconnresetCallback<Error, TReq, TRes>;
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;
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;
Comment thread
chimurai marked this conversation as resolved.
econnreset?: (err: Error, req: TReq, res: TRes, target: string | Partial<URL>) => void;
}

export type Logger = Pick<Console, 'info' | 'warn' | 'error'>;

export interface Options<TReq = http.IncomingMessage, TRes = http.ServerResponse>
extends httpProxy.ServerOptions {
export interface Options<
TReq = http.IncomingMessage,
TRes = 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.
Expand Down Expand Up @@ -122,9 +135,9 @@ export interface Options<TReq = http.IncomingMessage, TRes = http.ServerResponse
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/router.md
*/
router?:
| { [hostOrPath: string]: httpProxy.ServerOptions['target'] }
| ((req: TReq) => httpProxy.ServerOptions['target'])
| ((req: TReq) => Promise<httpProxy.ServerOptions['target']>);
| { [hostOrPath: string]: ProxyServerOptions['target'] }
| ((req: TReq) => ProxyServerOptions['target'])
| ((req: TReq) => Promise<ProxyServerOptions['target']>);
/**
* Log information from http-proxy-middleware
* @example
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"incremental": true,
"declaration": true,
"strict": true,
"noImplicitAny": false
"noImplicitAny": false,
"skipLibCheck": true
Comment thread
chimurai marked this conversation as resolved.
},
"include": ["./src"]
}
36 changes: 5 additions & 31 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1508,13 +1508,6 @@
resolved "https://registry.yarnpkg.com/@types/http-errors/-/http-errors-2.0.1.tgz#20172f9578b225f6c7da63446f56d4ce108d5a65"
integrity sha512-/K3ds8TRAfBvi5vfjuz8y6+GiAYBZ0x4tXv1Av6CWBWn0IlADc+ZX9pMq7oU0fNQPnBwIZl3rmeLp6SBApbxSQ==

"@types/http-proxy@^1.17.15":
version "1.17.15"
resolved "https://registry.yarnpkg.com/@types/http-proxy/-/http-proxy-1.17.15.tgz#12118141ce9775a6499ecb4c01d02f90fc839d36"
integrity sha512-25g5atgiVNTIv0LBDTg1H74Hvayx0ajtJPLLcYE3whFv75J0pWNtOBzaXJQgDTmrX1bx5U9YC2w/n65BN1HwRQ==
dependencies:
"@types/node" "*"

"@types/is-glob@4.0.4":
version "4.0.4"
resolved "https://registry.yarnpkg.com/@types/is-glob/-/is-glob-4.0.4.tgz#1d60fa47ff70abc97b4d9ea45328747c488b3a50"
Expand Down Expand Up @@ -2891,11 +2884,6 @@ eventemitter3@^3.1.0:
resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-3.1.2.tgz#2d3d48f9c346698fce83a85d7d664e98535df6e7"
integrity sha512-tvtQIeLVHjDkJYnzf2dgVMxfuSGJeM/7UCG17TT4EumTfNtF+0nebF/4zWOIkCreAbtNqhGEboB6BWrwqNaw4Q==

eventemitter3@^4.0.0:
version "4.0.7"
resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-4.0.7.tgz#2de9b68f6528d5644ef5c59526a1b4a07306169f"
integrity sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==

eventemitter3@^5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-5.0.1.tgz#53f5ffd0a492ac800721bb42c66b841de96423c4"
Expand Down Expand Up @@ -3139,11 +3127,6 @@ flatted@^3.2.9:
resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.4.2.tgz#f5c23c107f0f37de8dbdf24f13722b3b98d52726"
integrity sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==

follow-redirects@^1.0.0:
version "1.15.6"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.6.tgz#7f815c0cda4249c74ff09e95ef97c23b5fd0399b"
integrity sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==

foreground-child@^3.1.0:
version "3.3.1"
resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-3.3.1.tgz#32e8e9ed1b68a3497befb9ac2b6adf92a638576f"
Expand Down Expand Up @@ -3459,15 +3442,6 @@ http-proxy-agent@^7.0.0:
agent-base "^7.1.0"
debug "^4.3.4"

http-proxy@^1.18.1:
version "1.18.1"
resolved "https://registry.yarnpkg.com/http-proxy/-/http-proxy-1.18.1.tgz#401541f0534884bbf95260334e72f88ee3976549"
integrity sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==
dependencies:
eventemitter3 "^4.0.0"
follow-redirects "^1.0.0"
requires-port "^1.0.0"

http2-wrapper@^2.2.1:
version "2.2.1"
resolved "https://registry.yarnpkg.com/http2-wrapper/-/http2-wrapper-2.2.1.tgz#310968153dcdedb160d8b72114363ef5fce1f64a"
Expand All @@ -3492,6 +3466,11 @@ https-proxy-agent@^7.0.6:
agent-base "^7.1.2"
debug "4"

httpxy@^0.2.2:
version "0.2.2"
resolved "https://registry.yarnpkg.com/httpxy/-/httpxy-0.2.2.tgz#1603165cfd12087f2039c4a8532ce61eab5d84e5"
integrity sha512-QnS6mAOqvdmfctFaD/Kp5cwRMcaUhEmIyw2rjVYnhJb8EuAyd/79biT/50HUTKvq/PwoXYTP6J3d9TUxzHFZwA==

human-signals@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-2.1.0.tgz#dc91fcba42e4d06e4abaed33b3e7a3c02f514ea0"
Expand Down Expand Up @@ -5102,11 +5081,6 @@ require-from-string@^2.0.2:
resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-2.0.2.tgz#89a7fdd938261267318eafe14f9c32e598c36909"
integrity sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==

requires-port@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff"
integrity sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==

resolve-alpn@^1.2.0:
version "1.2.1"
resolved "https://registry.yarnpkg.com/resolve-alpn/-/resolve-alpn-1.2.1.tgz#b7adbdac3546aaaec20b45e7d8265927072726f9"
Expand Down
Loading