1+ import * as https from 'https' ;
12import * as express from 'express' ;
23import * as httpProxy from 'http-proxy' ;
34import { createConfig } from './config-factory' ;
@@ -12,6 +13,7 @@ export class HttpProxyMiddleware {
1213 private logger = getInstance ( ) ;
1314 private config ;
1415 private wsInternalSubscribed = false ;
16+ private serverOnCloseSubscribed = false ;
1517 private proxyOptions : Options ;
1618 private proxy : httpProxy ;
1719 private pathRewriter ;
@@ -58,13 +60,31 @@ export class HttpProxyMiddleware {
5860 next ( ) ;
5961 }
6062
63+ /**
64+ * Get the server object to subscribe to server events;
65+ * 'upgrade' for websocket and 'close' for graceful shutdown
66+ *
67+ * NOTE:
68+ * req.socket: node >= 13
69+ * req.connection: node < 13 (Remove this when node 12/13 support is dropped)
70+ */
71+ const server : https . Server = ( ( req . socket ?? req . connection ) as any ) ?. server ;
72+
73+ if ( server && ! this . serverOnCloseSubscribed ) {
74+ server . on ( 'close' , ( ) => {
75+ this . logger . info ( '[HPM] server close signal received: closing proxy server' ) ;
76+ this . proxy . close ( ) ;
77+ } ) ;
78+ this . serverOnCloseSubscribed = true ;
79+ }
80+
6181 if ( this . proxyOptions . ws === true ) {
6282 // use initial request to access the server object to subscribe to http upgrade event
63- this . catchUpgradeRequest ( ( req . connection as any ) . server ) ;
83+ this . catchUpgradeRequest ( server ) ;
6484 }
6585 } ;
6686
67- private catchUpgradeRequest = ( server ) => {
87+ private catchUpgradeRequest = ( server : https . Server ) => {
6888 if ( ! this . wsInternalSubscribed ) {
6989 server . on ( 'upgrade' , this . handleUpgrade ) ;
7090 // prevent duplicate upgrade handling;
0 commit comments