Skip to content

Commit

Permalink
fix(sse): fix sse when backend restarts
Browse files Browse the repository at this point in the history
  • Loading branch information
chimurai committed Apr 22, 2023
1 parent a2d2bb7 commit abcf5ee
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions src/plugins/default/debug-proxy-errors-plugin.ts
Expand Up @@ -7,7 +7,7 @@ const debug = Debug.extend('debug-proxy-errors-plugin');
* Subscribe to {@link https://www.npmjs.com/package/http-proxy#listening-for-proxy-events http-proxy error events} to prevent server from crashing.
* Errors are logged with {@link https://www.npmjs.com/package/debug debug} library.
*/
export const debugProxyErrorsPlugin: Plugin = (proxyServer): void => {
export const debugProxyErrorsPlugin: Plugin = (proxyServer, options): void => {
/**
* http-proxy doesn't handle any errors by default (https://github.com/http-party/node-http-proxy#listening-for-proxy-events)
* Prevent server from crashing when http-proxy errors (uncaught errors)
Expand All @@ -22,18 +22,34 @@ export const debugProxyErrorsPlugin: Plugin = (proxyServer): void => {
});
});

/**
* 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) => {
/**
* 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
*/
res.on('close', () => {
if (!res.writableEnded) {
debug('Destroying proxyRes in proxyRes close event');
debug('res close event received, destroying proxyRes');
proxyRes.destroy();
}
});

/**
* Fix SSE when backend closes/restarts
* @link https://github.com/chimurai/http-proxy-middleware/discussions/765
*/
proxyRes.on('close', () => {
// don't destroy res when using it in response interceptor
if (options.selfHandleResponse) {
return;
}

if (!res.writableEnded) {
debug('proxyRes close event received, destroying res');
res.destroy();
}
});
});

/**
Expand Down

0 comments on commit abcf5ee

Please sign in to comment.