Skip to content

Commit

Permalink
Fix external rewrite with body (#49487)
Browse files Browse the repository at this point in the history
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: #48040
  • Loading branch information
ijjk committed May 8, 2023
1 parent 20e1349 commit 71d3543
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/next/src/server/next-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
})
}
})

Expand Down
6 changes: 6 additions & 0 deletions test/e2e/middleware-rewrites/app/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')) {
request.nextUrl.pathname = '/static-ssg/post-1'
return NextResponse.rewrite(request.nextUrl)
Expand Down
5 changes: 5 additions & 0 deletions test/e2e/middleware-rewrites/app/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ module.exports = {
source: '/config-rewrite-to-dynamic-static/:rewriteSlug',
destination: '/ssg',
},
{
source: '/external-rewrite-body',
destination:
'https://next-data-api-endpoint.vercel.app/api/echo-body',
},
],
fallback: [],
}
Expand Down
22 changes: 22 additions & 0 deletions test/e2e/middleware-rewrites/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,28 @@ describe('Middleware Rewrite', () => {
})

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 () => {
const browser = await webdriver(next.url, '/rewrite-to-static')

Expand Down

0 comments on commit 71d3543

Please sign in to comment.