Unverified Commit 71d35436 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix external rewrite with body (#49487)

This ensures we use the proper body stream when rewriting to an external
resource as currently it tries to consume an already read body stream.

Fixes: https://github.com/vercel/next.js/issues/48040
parent 20e13490
...@@ -860,7 +860,12 @@ export default class NextNodeServer extends BaseServer { ...@@ -860,7 +860,12 @@ export default class NextNodeServer extends BaseServer {
} }
}) })
}) })
proxy.web(req.originalRequest, res.originalResponse) proxy.web(req.originalRequest, res.originalResponse, {
buffer: getRequestMeta(
req,
'__NEXT_CLONABLE_BODY'
)?.cloneBodyStream(),
})
} }
}) })
......
...@@ -19,6 +19,12 @@ export async function middleware(request) { ...@@ -19,6 +19,12 @@ export async function middleware(request) {
}) })
} }
if (url.pathname.includes('/middleware-external-rewrite-body')) {
return NextResponse.rewrite(
'https://next-data-api-endpoint.vercel.app/api/echo-body'
)
}
if (url.pathname.includes('/rewrite-to-static')) { if (url.pathname.includes('/rewrite-to-static')) {
request.nextUrl.pathname = '/static-ssg/post-1' request.nextUrl.pathname = '/static-ssg/post-1'
return NextResponse.rewrite(request.nextUrl) return NextResponse.rewrite(request.nextUrl)
......
...@@ -24,6 +24,11 @@ module.exports = { ...@@ -24,6 +24,11 @@ module.exports = {
source: '/config-rewrite-to-dynamic-static/:rewriteSlug', source: '/config-rewrite-to-dynamic-static/:rewriteSlug',
destination: '/ssg', destination: '/ssg',
}, },
{
source: '/external-rewrite-body',
destination:
'https://next-data-api-endpoint.vercel.app/api/echo-body',
},
], ],
fallback: [], fallback: [],
} }
......
...@@ -23,6 +23,28 @@ describe('Middleware Rewrite', () => { ...@@ -23,6 +23,28 @@ describe('Middleware Rewrite', () => {
}) })
function tests() { function tests() {
it('should handle next.config.js rewrite with body correctly', async () => {
const body = JSON.stringify({ hello: 'world' })
const res = await next.fetch('/external-rewrite-body', {
redirect: 'manual',
method: 'POST',
body,
})
expect(res.status).toBe(200)
expect(await res.text()).toEqual(body)
})
it('should handle middleware rewrite with body correctly', async () => {
const body = JSON.stringify({ hello: 'world' })
const res = await next.fetch('/middleware-external-rewrite-body', {
redirect: 'manual',
method: 'POST',
body,
})
expect(res.status).toBe(200)
expect(await res.text()).toEqual(body)
})
it('should handle static dynamic rewrite from middleware correctly', async () => { it('should handle static dynamic rewrite from middleware correctly', async () => {
const browser = await webdriver(next.url, '/rewrite-to-static') const browser = await webdriver(next.url, '/rewrite-to-static')
......
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