Skip to content

Commit feda5d8

Browse files
kevvaijjk
andauthoredMar 28, 2025··
fix: make sure body can be read using nodejs runtime in middleware (#77553)
This fixes an issue where the body couldn't be read when running the middleware with the `nodejs` runtime. When running it in the `edge` runtime, `cloneBodyStream()` is ran [here](https://github.com/vercel/next.js/blob/ca4a18789d37dbd01ca3c88091d1f86134072dee/packages/next/src/server/web/sandbox/sandbox.ts#L104) so we need to do the same for the `nodejs` runtime. Fixes #77551 --------- Co-authored-by: JJ Kasper <[email protected]>
1 parent a41152e commit feda5d8

File tree

4 files changed

+25
-1
lines changed

4 files changed

+25
-1
lines changed
 

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

+6-1
Original file line numberDiff line numberDiff line change
@@ -1605,7 +1605,12 @@ export default class NextNodeServer extends BaseServer<
16051605

16061606
result = await adapterFn({
16071607
handler: middlewareModule.middleware || middlewareModule,
1608-
request: requestData,
1608+
request: {
1609+
...requestData,
1610+
body: !['HEAD', 'GET'].includes(params.request.method)
1611+
? requestData.body?.cloneBodyStream()
1612+
: undefined,
1613+
},
16091614
page: 'middleware',
16101615
})
16111616
} else {

‎test/e2e/middleware-general/app/middleware-node.js

+4
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,10 @@ export async function middleware(request) {
253253
throw new Error('test error')
254254
}
255255

256+
if (url.pathname === '/request-body' && request.method === 'POST') {
257+
return NextResponse.json(await request.json())
258+
}
259+
256260
const original = new URL(request.url)
257261
return NextResponse.next({
258262
headers: {

‎test/e2e/middleware-general/app/middleware.js

+4
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,10 @@ export async function middleware(request) {
252252
throw new Error('test error')
253253
}
254254

255+
if (url.pathname === '/request-body' && request.method === 'POST') {
256+
return NextResponse.json(await request.json())
257+
}
258+
255259
const original = new URL(request.url)
256260
return NextResponse.next({
257261
headers: {

‎test/e2e/middleware-general/test/index.test.ts

+11
Original file line numberDiff line numberDiff line change
@@ -824,6 +824,17 @@ describe('Middleware Runtime', () => {
824824
}/sha.json?hello=goodbye`,
825825
])
826826
})
827+
828+
it(`should read request body`, async () => {
829+
const body = { hello: 'world' }
830+
const res = await fetchViaHTTP(next.url, '/request-body', undefined, {
831+
body: JSON.stringify(body),
832+
headers: { 'content-type': 'application/json' },
833+
method: 'POST',
834+
})
835+
836+
expect(await res.json()).toEqual(body)
837+
})
827838
}
828839
describe('with i18n', () => {
829840
setup({ i18n: true })

0 commit comments

Comments
 (0)
Please sign in to comment.