Unverified Commit d97af317 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix header resent when error occured (#55619)

When errors are thrown in middleware it could re-send headers for the same response

```
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at __node_internal_captureLargerStackTrace (node:internal/errors:490:5)
    at new NodeError (node:internal/errors:399:5)
    at ServerResponse.setHeader (node:_http_outgoing:645:11)
    at origSetHeader (/next.js/packages/next/src/server/base-server.ts:777:16)
    at ServerResponse._res.setHeader (/next.js/packages/next/src/server/base-s
erver.ts:777:16)
    at setHeader (/next.js/packages/next/src/server/base-http/node.ts:84:15)
    at renderErrorImpl (/next.js/packages/next/src/server/base-server.ts:2790:
11)
    at <anonymous> (/next.js/packages/next/src/server/base-server.ts:2777:19)
    at trace (/next.js/packages/next/src/server/lib/trace/tracer.ts:213:14)
    at DevServer.renderError (/next.js/packages/next/src/server/base-server.ts
:2776:24)
    at DevServer.renderError (/next.js/packages/next/src/server/next-server.ts
:1299:18)
    at DevServer.handleRequestImpl (/next.js/packages/next/src/server/base-ser
ver.ts:1185:23) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
```

Migrate middleware-errors test to e2e test to avoid flaky assertion due to duplicated logging collected in integration test.

Closes NEXT-1629
parent 72434c27
...@@ -751,6 +751,11 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -751,6 +751,11 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const origSetHeader = _res.setHeader.bind(_res) const origSetHeader = _res.setHeader.bind(_res)
_res.setHeader = (name: string, val: string | string[]) => { _res.setHeader = (name: string, val: string | string[]) => {
// When renders /_error after page is failed,
// it could attempt to set headers after headers
if (_res.headersSent) {
return
}
if (name.toLowerCase() === 'set-cookie') { if (name.toLowerCase() === 'set-cookie') {
const middlewareValue = getRequestMeta(req, '_nextMiddlewareCookie') const middlewareValue = getRequestMeta(req, '_nextMiddlewareCookie')
......
import { check, getRedboxSource, hasRedbox } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'middleware - development errors',
{
files: __dirname,
env: { __NEXT_TEST_WITH_DEVTOOL: '1' },
},
({ next }) => {
beforeEach(async () => {
await next.stop()
})
describe('when middleware throws synchronously', () => {
beforeEach(async () => {
await next.patchFile(
'middleware.js',
`
export default function () {
throw new Error('boom')
}`
)
await next.start()
})
it('logs the error correctly', async () => {
await next.fetch('/')
const output = stripAnsi(next.cliOutput)
await check(
() => stripAnsi(next.cliOutput),
new RegExp(
`middleware.js \\(\\d+:\\d+\\) @ Object.default \\[as handler\\]\\s*\\w+\\s*boom`,
'm'
)
)
expect(output).not.toContain(
'webpack-internal:///(middleware)/./middleware.js'
)
})
it('renders the error correctly and recovers', async () => {
const browser = await next.browser('/')
expect(await hasRedbox(browser, true)).toBe(true)
await next.patchFile('middleware.js', `export default function () {}`)
await hasRedbox(browser, false)
})
})
describe('when middleware contains an unhandled rejection', () => {
beforeEach(async () => {
await next.patchFile(
'middleware.js',
`
import { NextResponse } from 'next/server'
async function throwError() {
throw new Error('async boom!')
}
export default function () {
throwError()
return NextResponse.next()
}`
)
await next.start()
})
it('logs the error correctly', async () => {
await next.fetch('/')
await check(
() => stripAnsi(next.cliOutput),
new RegExp(`unhandledRejection: Error: async boom!`, 'm')
)
// expect(output).not.toContain(
// 'webpack-internal:///(middleware)/./middleware.js'
// )
})
it('does not render the error', async () => {
const browser = await next.browser('/')
expect(await hasRedbox(browser, false)).toBe(false)
expect(await browser.elementByCss('#page-title')).toBeTruthy()
})
})
describe('when running invalid dynamic code with eval', () => {
beforeEach(async () => {
await next.patchFile(
'middleware.js',
`
import { NextResponse } from 'next/server'
export default function () {
eval('test')
return NextResponse.next()
}`
)
await next.start()
})
it('logs the error correctly', async () => {
await next.fetch('/')
const output = stripAnsi(next.cliOutput)
await check(
() => stripAnsi(next.cliOutput),
new RegExp(
`middleware.js \\(\\d+:\\d+\\) @ eval\\s*\\w+\\s*test is not defined`,
'm'
)
)
expect(output).not.toContain(
'webpack-internal:///(middleware)/./middleware.js'
)
})
it('renders the error correctly and recovers', async () => {
const browser = await next.browser('/')
expect(await hasRedbox(browser, true)).toBe(true)
expect(await getRedboxSource(browser)).toContain(`eval('test')`)
await next.patchFile('middleware.js', `export default function () {}`)
await hasRedbox(browser, false)
})
})
describe('when throwing while loading the module', () => {
beforeEach(async () => {
await next.patchFile(
'middleware.js',
`
import { NextResponse } from 'next/server'
throw new Error('booooom!')
export default function () {
return NextResponse.next()
}`
)
await next.start()
})
it('logs the error correctly', async () => {
await next.fetch('/')
const output = stripAnsi(next.cliOutput)
await check(
() => stripAnsi(next.cliOutput),
new RegExp(
`middleware.js \\(\\d+:\\d+\\) @ <unknown>\\s*\\w+\\s*booooom!`,
'm'
)
)
expect(output).not.toContain(
'webpack-internal:///(middleware)/./middleware.js'
)
})
it('renders the error correctly and recovers', async () => {
const browser = await next.browser('/')
expect(await hasRedbox(browser, true)).toBe(true)
expect(await getRedboxSource(browser)).toContain(
`throw new Error('booooom!')`
)
await next.patchFile('middleware.js', `export default function () {}`)
await hasRedbox(browser, false)
})
})
describe('when there is an unhandled rejection while loading the module', () => {
beforeEach(async () => {
await next.patchFile(
'middleware.js',
`
import { NextResponse } from 'next/server'
(async function(){
throw new Error('you shall see me')
})()
export default function () {
return NextResponse.next()
}`
)
await next.start()
})
it('logs the error correctly', async () => {
await next.fetch('/')
await check(
() => stripAnsi(next.cliOutput),
new RegExp(`unhandledRejection: Error: you shall see me`, 'm')
)
// expect(output).not.toContain(
// 'webpack-internal:///(middleware)/./middleware.js'
// )
})
it('does not render the error', async () => {
const browser = await next.browser('/')
expect(await hasRedbox(browser, false)).toBe(false)
expect(await browser.elementByCss('#page-title')).toBeTruthy()
})
})
describe('when there is an unhandled rejection while loading a dependency', () => {
beforeEach(async () => {
await next.patchFile(
'middleware.js',
`
import { NextResponse } from 'next/server'
import './lib/unhandled'
export default function () {
return NextResponse.next()
}`
)
await next.start()
})
it('logs the error correctly', async () => {
await next.fetch('/')
const output = stripAnsi(next.cliOutput)
await check(
() => stripAnsi(next.cliOutput),
new RegExp(
` uncaughtException: Error: This file asynchronously fails while loading`,
'm'
)
)
expect(output).not.toContain(
'webpack-internal:///(middleware)/./middleware.js'
)
})
it('does not render the error', async () => {
const browser = await next.browser('/')
expect(await hasRedbox(browser, false)).toBe(false)
expect(await browser.elementByCss('#page-title')).toBeTruthy()
})
})
describe('when there is a compilation error from boot', () => {
beforeEach(async () => {
await next.patchFile('middleware.js', `export default function () }`)
await next.start()
})
it('logs the error correctly', async () => {
await next.fetch('/')
expect(next.cliOutput).toContain(`Expected '{', got '}'`)
expect(next.cliOutput.split(`Expected '{', got '}'`).length).toEqual(2)
})
it('renders the error correctly and recovers', async () => {
const browser = await next.browser('/')
expect(await hasRedbox(browser, true)).toBe(true)
expect(
await browser
.elementByCss('#nextjs__container_build_error_label')
.text()
).toEqual('Failed to compile')
await next.patchFile('middleware.js', `export default function () {}`)
await hasRedbox(browser, false)
expect(await browser.elementByCss('#page-title')).toBeTruthy()
})
})
describe('when there is a compilation error after boot', () => {
beforeEach(async () => {
await next.patchFile('middleware.js', `export default function () {}`)
await next.start()
})
it('logs the error correctly', async () => {
await next.fetch('/')
await next.patchFile('middleware.js', `export default function () }`)
await check(() => {
expect(next.cliOutput).toContain(`Expected '{', got '}'`)
expect(next.cliOutput.split(`Expected '{', got '}'`).length).toEqual(
2
)
return 'success'
}, 'success')
})
it('renders the error correctly and recovers', async () => {
const browser = await next.browser('/')
expect(await hasRedbox(browser, false)).toBe(false)
await next.patchFile('middleware.js', `export default function () }`)
expect(await hasRedbox(browser, true)).toBe(true)
await next.patchFile('middleware.js', `export default function () {}`)
expect(await hasRedbox(browser, false)).toBe(false)
expect(await browser.elementByCss('#page-title')).toBeTruthy()
})
})
}
)
import {
check,
fetchViaHTTP,
File,
findPort,
getRedboxSource,
hasRedbox,
killApp,
launchApp,
} from 'next-test-utils'
import { join } from 'path'
import stripAnsi from 'strip-ansi'
import webdriver from 'next-webdriver'
const context = {
appDir: join(__dirname, '../'),
buildLogs: { output: '', stdout: '', stderr: '' },
logs: { output: '', stdout: '', stderr: '' },
middleware: new File(join(__dirname, '../middleware.js')),
page: new File(join(__dirname, '../pages/index.js')),
}
describe('Middleware development errors', () => {
beforeEach(async () => {
context.logs = { output: '', stdout: '', stderr: '' }
context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
onStdout(msg) {
context.logs.output += msg
context.logs.stdout += msg
},
onStderr(msg) {
context.logs.output += msg
context.logs.stderr += msg
},
})
})
afterEach(async () => {
context.middleware.restore()
context.page.restore()
if (context.app) {
await killApp(context.app)
}
})
describe('when middleware throws synchronously', () => {
beforeEach(() => {
context.middleware.write(`
export default function () {
throw new Error('boom')
}`)
})
it('logs the error correctly', async () => {
await fetchViaHTTP(context.appPort, '/')
const output = stripAnsi(context.logs.output)
await check(
() => stripAnsi(context.logs.output),
new RegExp(
`middleware.js \\(\\d+:\\d+\\) @ Object.default \\[as handler\\]\\s*\\w+\\s*boom`,
'm'
)
)
expect(output).not.toContain(
'webpack-internal:///(middleware)/./middleware.js'
)
})
it('renders the error correctly and recovers', async () => {
const browser = await webdriver(context.appPort, '/')
expect(await hasRedbox(browser, true)).toBe(true)
context.middleware.write(`export default function () {}`)
await hasRedbox(browser, false)
})
})
describe('when middleware contains an unhandled rejection', () => {
beforeEach(() => {
context.middleware.write(`
import { NextResponse } from 'next/server'
async function throwError() {
throw new Error('async boom!')
}
export default function () {
throwError()
return NextResponse.next()
}`)
})
it('logs the error correctly', async () => {
await fetchViaHTTP(context.appPort, '/')
await check(
() => stripAnsi(context.logs.output),
new RegExp(`unhandledRejection: Error: async boom!`, 'm')
)
// expect(output).not.toContain(
// 'webpack-internal:///(middleware)/./middleware.js'
// )
})
it('does not render the error', async () => {
const browser = await webdriver(context.appPort, '/')
expect(await hasRedbox(browser, false)).toBe(false)
expect(await browser.elementByCss('#page-title')).toBeTruthy()
})
})
describe('when running invalid dynamic code with eval', () => {
beforeEach(() => {
context.middleware.write(`
import { NextResponse } from 'next/server'
export default function () {
eval('test')
return NextResponse.next()
}`)
})
it('logs the error correctly', async () => {
await fetchViaHTTP(context.appPort, '/')
const output = stripAnsi(context.logs.output)
await check(
() => stripAnsi(context.logs.output),
new RegExp(
`middleware.js \\(\\d+:\\d+\\) @ eval\\s*\\w+\\s*test is not defined`,
'm'
)
)
expect(output).not.toContain(
'webpack-internal:///(middleware)/./middleware.js'
)
})
it('renders the error correctly and recovers', async () => {
const browser = await webdriver(context.appPort, '/')
expect(await hasRedbox(browser, true)).toBe(true)
expect(await getRedboxSource(browser)).toContain(`eval('test')`)
context.middleware.write(`export default function () {}`)
await hasRedbox(browser, false)
})
})
describe('when throwing while loading the module', () => {
beforeEach(() => {
context.middleware.write(`
import { NextResponse } from 'next/server'
throw new Error('booooom!')
export default function () {
return NextResponse.next()
}`)
})
it('logs the error correctly', async () => {
await fetchViaHTTP(context.appPort, '/')
const output = stripAnsi(context.logs.output)
await check(
() => stripAnsi(context.logs.output),
new RegExp(
`middleware.js \\(\\d+:\\d+\\) @ <unknown>\\s*\\w+\\s*booooom!`,
'm'
)
)
expect(output).not.toContain(
'webpack-internal:///(middleware)/./middleware.js'
)
})
it('renders the error correctly and recovers', async () => {
const browser = await webdriver(context.appPort, '/')
expect(await hasRedbox(browser, true)).toBe(true)
expect(await getRedboxSource(browser)).toContain(
`throw new Error('booooom!')`
)
context.middleware.write(`export default function () {}`)
await hasRedbox(browser, false)
})
})
describe('when there is an unhandled rejection while loading the module', () => {
beforeEach(() => {
context.middleware.write(`
import { NextResponse } from 'next/server'
(async function(){
throw new Error('you shall see me')
})()
export default function () {
return NextResponse.next()
}`)
})
it('logs the error correctly', async () => {
await fetchViaHTTP(context.appPort, '/')
await check(
() => stripAnsi(context.logs.output),
new RegExp(`unhandledRejection: Error: you shall see me`, 'm')
)
// expect(output).not.toContain(
// 'webpack-internal:///(middleware)/./middleware.js'
// )
})
it('does not render the error', async () => {
const browser = await webdriver(context.appPort, '/')
expect(await hasRedbox(browser, false)).toBe(false)
expect(await browser.elementByCss('#page-title')).toBeTruthy()
})
})
describe('when there is an unhandled rejection while loading a dependency', () => {
beforeEach(() => {
context.middleware.write(`
import { NextResponse } from 'next/server'
import './lib/unhandled'
export default function () {
return NextResponse.next()
}`)
})
it('logs the error correctly', async () => {
await fetchViaHTTP(context.appPort, '/')
const output = stripAnsi(context.logs.output)
await check(
() => stripAnsi(context.logs.output),
new RegExp(
` uncaughtException: Error: This file asynchronously fails while loading`,
'm'
)
)
expect(output).not.toContain(
'webpack-internal:///(middleware)/./middleware.js'
)
})
it('does not render the error', async () => {
const browser = await webdriver(context.appPort, '/')
expect(await hasRedbox(browser, false)).toBe(false)
expect(await browser.elementByCss('#page-title')).toBeTruthy()
})
})
describe('when there is a compilation error from boot', () => {
beforeEach(() => {
context.middleware.write(`export default function () }`)
})
it('logs the error correctly', async () => {
await fetchViaHTTP(context.appPort, '/')
expect(context.logs.output).toContain(`Expected '{', got '}'`)
// TODO: investigate occasional duplicate errors causing flakiness
// expect(context.logs.output.split(`Expected '{', got '}'`).length).toEqual(
// 2
// )
})
it('renders the error correctly and recovers', async () => {
const browser = await webdriver(context.appPort, '/')
expect(await hasRedbox(browser, true)).toBe(true)
expect(
await browser
.elementByCss('#nextjs__container_build_error_label')
.text()
).toEqual('Failed to compile')
context.middleware.write(`export default function () {}`)
await hasRedbox(browser, false)
expect(await browser.elementByCss('#page-title')).toBeTruthy()
})
})
describe('when there is a compilation error after boot', () => {
beforeEach(() => {
context.middleware.write(`export default function () {}`)
})
it('logs the error correctly', async () => {
await fetchViaHTTP(context.appPort, '/')
context.middleware.write(`export default function () }`)
await check(() => {
expect(context.logs.output).toContain(`Expected '{', got '}'`)
expect(
context.logs.output.split(`Expected '{', got '}'`).length
).toEqual(2)
return 'success'
}, 'success')
})
it('renders the error correctly and recovers', async () => {
const browser = await webdriver(context.appPort, '/')
expect(await hasRedbox(browser, false)).toBe(false)
context.middleware.write(`export default function () }`)
expect(await hasRedbox(browser, true)).toBe(true)
context.middleware.write(`export default function () {}`)
expect(await hasRedbox(browser, false)).toBe(false)
expect(await browser.elementByCss('#page-title')).toBeTruthy()
})
})
})
...@@ -403,7 +403,8 @@ export function runNextCommandDev( ...@@ -403,7 +403,8 @@ export function runNextCommandDev(
} }
function handleStderr(data) { function handleStderr(data) {
const message = stripAnsi(data.toString()) as any const message = data.toString()
if (typeof opts.onStderr === 'function') { if (typeof opts.onStderr === 'function') {
opts.onStderr(message) opts.onStderr(message)
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment