From cac9ccf9ce077238572c1ce356feb64ef6650103 Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Mon, 26 Apr 2021 08:40:32 -0500 Subject: [PATCH] Ensure proxy rewrite does not hang on error (#24394) * Ensure proxy rewrite does not hang on error * remove logs * Listen to req close --- .../next/next-server/server/next-server.ts | 23 ++++++++++++++++--- test/integration/custom-routes/next.config.js | 4 ++++ .../custom-routes/test/index.test.js | 13 +++++++++++ 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/packages/next/next-server/server/next-server.ts b/packages/next/next-server/server/next-server.ts index ecd8042b6a8f1..7c5d7b559df9c 100644 --- a/packages/next/next-server/server/next-server.ts +++ b/packages/next/next-server/server/next-server.ts @@ -924,12 +924,29 @@ export default class Server { target, changeOrigin: true, ignorePath: true, + proxyTimeout: 30_000, // limit proxying to 30 seconds }) - proxy.web(req, res) - proxy.on('error', (err: Error) => { - console.error(`Error occurred proxying ${target}`, err) + await new Promise((proxyResolve, proxyReject) => { + let finished = false + + proxy.on('proxyReq', (proxyReq) => { + proxyReq.on('close', () => { + if (!finished) { + finished = true + proxyResolve(true) + } + }) + }) + proxy.on('error', (err) => { + if (!finished) { + finished = true + proxyReject(err) + } + }) + proxy.web(req, res) }) + return { finished: true, } diff --git a/test/integration/custom-routes/next.config.js b/test/integration/custom-routes/next.config.js index c5ac688266816..7ba28f11ce1f2 100644 --- a/test/integration/custom-routes/next.config.js +++ b/test/integration/custom-routes/next.config.js @@ -11,6 +11,10 @@ module.exports = { }, ] : []), + { + source: '/to-nowhere', + destination: 'http://localhost:12233', + }, { source: '/rewriting-to-auto-export', destination: '/auto-export/hello?rewrite=1', diff --git a/test/integration/custom-routes/test/index.test.js b/test/integration/custom-routes/test/index.test.js index 725809849fc37..cd8f2161c5937 100644 --- a/test/integration/custom-routes/test/index.test.js +++ b/test/integration/custom-routes/test/index.test.js @@ -38,6 +38,14 @@ let appPort let app const runTests = (isDev = false) => { + it('should not hang when proxy rewrite fails', async () => { + const res = await fetchViaHTTP(appPort, '/to-nowhere', undefined, { + timeout: 5000, + }) + + expect(res.status).toBe(500) + }) + it('should parse params correctly for rewrite to auto-export dynamic page', async () => { const browser = await webdriver(appPort, '/rewriting-to-auto-export') const text = await browser.eval(() => document.documentElement.innerHTML) @@ -1395,6 +1403,11 @@ const runTests = (isDev = false) => { }, ], afterFiles: [ + { + destination: 'http://localhost:12233', + regex: normalizeRegEx('^\\/to-nowhere$'), + source: '/to-nowhere', + }, { destination: '/auto-export/hello?rewrite=1', regex: normalizeRegEx('^\\/rewriting-to-auto-export$'),