Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix post request hangs when no body is consumed on middleware #35131

Merged
merged 2 commits into from Mar 8, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
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')
})
})