Skip to content

Commit

Permalink
fix post request hangs when no body is consumed on middleware (#35131)
Browse files Browse the repository at this point in the history
fixes #34966

Wait for reading original request body before overwriting the request properties with `originalBody?.finalize()` call since it caused the problem when middleware does not read request body

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
  • Loading branch information
nkzawa committed Mar 8, 2022
1 parent d141376 commit eb87845
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
8 changes: 7 additions & 1 deletion packages/next/server/body-streams.ts
Expand Up @@ -58,14 +58,20 @@ export function clonableBodyForRequest<T extends IncomingMessage>(
) {
let bufferedBodyStream: BodyStream | null = null

const endPromise = new Promise((resolve, reject) => {
incomingMessage.on('end', resolve)
incomingMessage.on('error', reject)
})

return {
/**
* Replaces the original request body if necessary.
* This is done because once we read the body from the original request,
* we can't read it again.
*/
finalize(): void {
async finalize(): Promise<void> {
if (bufferedBodyStream) {
await endPromise
replaceRequestBody(
incomingMessage,
bodyStreamToNodeStream(bufferedBodyStream)
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/next-server.ts
Expand Up @@ -1314,7 +1314,7 @@ export default class NextNodeServer extends BaseServer {
}
}

originalBody?.finalize()
await originalBody?.finalize()

return result
}
Expand Down
32 changes: 31 additions & 1 deletion test/production/reading-request-body-in-middleware/index.test.ts
Expand Up @@ -16,7 +16,11 @@ describe('reading request body in middleware', () => {
return new Response('No body', { status: 400 });
}
const json = await request.json();
let json;
if (!request.nextUrl.searchParams.has("no_reading")) {
json = await request.json();
}
if (request.nextUrl.searchParams.has("next")) {
const res = NextResponse.next();
Expand Down Expand Up @@ -141,4 +145,30 @@ describe('reading request body in middleware', () => {
})
expect(response.headers.get('x-from-root-middleware')).toEqual('1')
})

it('passes the body to the api endpoint when no body is consumed on middleware', async () => {
const response = await fetchViaHTTP(
next.url,
'/api/hi',
{
next: '1',
no_reading: '1',
},
{
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({
foo: 'bar',
}),
}
)
expect(response.status).toEqual(200)
expect(await response.json()).toEqual({
foo: 'bar',
api: true,
})
expect(response.headers.get('x-from-root-middleware')).toEqual('1')
})
})

0 comments on commit eb87845

Please sign in to comment.