Skip to content

Commit cac9ccf

Browse files
authoredApr 26, 2021
Ensure proxy rewrite does not hang on error (#24394)
* Ensure proxy rewrite does not hang on error * remove logs * Listen to req close
1 parent cf4ba8d commit cac9ccf

File tree

3 files changed

+37
-3
lines changed

3 files changed

+37
-3
lines changed
 

‎packages/next/next-server/server/next-server.ts

+20-3
Original file line numberDiff line numberDiff line change
@@ -924,12 +924,29 @@ export default class Server {
924924
target,
925925
changeOrigin: true,
926926
ignorePath: true,
927+
proxyTimeout: 30_000, // limit proxying to 30 seconds
927928
})
928-
proxy.web(req, res)
929929

930-
proxy.on('error', (err: Error) => {
931-
console.error(`Error occurred proxying ${target}`, err)
930+
await new Promise((proxyResolve, proxyReject) => {
931+
let finished = false
932+
933+
proxy.on('proxyReq', (proxyReq) => {
934+
proxyReq.on('close', () => {
935+
if (!finished) {
936+
finished = true
937+
proxyResolve(true)
938+
}
939+
})
940+
})
941+
proxy.on('error', (err) => {
942+
if (!finished) {
943+
finished = true
944+
proxyReject(err)
945+
}
946+
})
947+
proxy.web(req, res)
932948
})
949+
933950
return {
934951
finished: true,
935952
}

‎test/integration/custom-routes/next.config.js

+4
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ module.exports = {
1111
},
1212
]
1313
: []),
14+
{
15+
source: '/to-nowhere',
16+
destination: 'http://localhost:12233',
17+
},
1418
{
1519
source: '/rewriting-to-auto-export',
1620
destination: '/auto-export/hello?rewrite=1',

‎test/integration/custom-routes/test/index.test.js

+13
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ let appPort
3838
let app
3939

4040
const runTests = (isDev = false) => {
41+
it('should not hang when proxy rewrite fails', async () => {
42+
const res = await fetchViaHTTP(appPort, '/to-nowhere', undefined, {
43+
timeout: 5000,
44+
})
45+
46+
expect(res.status).toBe(500)
47+
})
48+
4149
it('should parse params correctly for rewrite to auto-export dynamic page', async () => {
4250
const browser = await webdriver(appPort, '/rewriting-to-auto-export')
4351
const text = await browser.eval(() => document.documentElement.innerHTML)
@@ -1395,6 +1403,11 @@ const runTests = (isDev = false) => {
13951403
},
13961404
],
13971405
afterFiles: [
1406+
{
1407+
destination: 'http://localhost:12233',
1408+
regex: normalizeRegEx('^\\/to-nowhere$'),
1409+
source: '/to-nowhere',
1410+
},
13981411
{
13991412
destination: '/auto-export/hello?rewrite=1',
14001413
regex: normalizeRegEx('^\\/rewriting-to-auto-export$'),

0 commit comments

Comments
 (0)
Please sign in to comment.