Skip to content

Commit

Permalink
Ensure proxy rewrite does not hang on error (#24394)
Browse files Browse the repository at this point in the history
* Ensure proxy rewrite does not hang on error

* remove logs

* Listen to req close
  • Loading branch information
ijjk authored Apr 26, 2021
1 parent cf4ba8d commit cac9ccf
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
23 changes: 20 additions & 3 deletions packages/next/next-server/server/next-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down
4 changes: 4 additions & 0 deletions test/integration/custom-routes/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ module.exports = {
},
]
: []),
{
source: '/to-nowhere',
destination: 'http://localhost:12233',
},
{
source: '/rewriting-to-auto-export',
destination: '/auto-export/hello?rewrite=1',
Expand Down
13 changes: 13 additions & 0 deletions test/integration/custom-routes/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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$'),
Expand Down

0 comments on commit cac9ccf

Please sign in to comment.