Skip to content

Commit 6139f4b

Browse files
unstubbableelishagreenwaldLiamBozkmaclip
authored
[backport] Fix server action forwarding loop with middleware rewrites (#93919)
Backports: - #93792 Co-authored-by: Elisha Greenwald <[email protected]> Co-authored-by: LiamBoz <[email protected]> Co-authored-by: kmaclip <[email protected]>
1 parent c021d10 commit 6139f4b

8 files changed

Lines changed: 116 additions & 6 deletions

File tree

‎packages/next/src/server/app-render/action-handler.ts‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -278,9 +278,18 @@ async function createForwardedActionResponse(
278278
}
279279

280280
return new FlightRenderResult(response.body!)
281-
} else {
282-
// Since we aren't consuming the response body, we cancel it to avoid memory leaks
283-
response.body?.cancel()
281+
}
282+
283+
// Since we aren't consuming the response body, we cancel it to avoid memory leaks
284+
response.body?.cancel()
285+
286+
// Pass the action-not-found marker through so the client throws
287+
// UnrecognizedActionError instead of a generic "unexpected response".
288+
if (response.headers.get(NEXT_ACTION_NOT_FOUND_HEADER) === '1') {
289+
res.setHeader(NEXT_ACTION_NOT_FOUND_HEADER, '1')
290+
res.setHeader('content-type', 'text/plain')
291+
res.statusCode = 404
292+
return RenderResult.fromStatic('Server action not found.', 'text/plain')
284293
}
285294
} catch (err) {
286295
// we couldn't stream the forwarded response, so we'll just return an empty response
@@ -707,11 +716,15 @@ export async function handleAction({
707716

708717
const actionWasForwarded = Boolean(req.headers['x-action-forwarded'])
709718

710-
if (actionId) {
719+
// Only attempt to forward if this request has not already been forwarded.
720+
// Otherwise middleware that rewrites the action POST can cause the receiving
721+
// worker to forward again, looping indefinitely.
722+
if (actionId && !actionWasForwarded) {
711723
const forwardedWorker = selectWorkerForForwarding(actionId, page)
712724

713-
// If forwardedWorker is truthy, it means there isn't a worker for the action
714-
// in the current handler, so we forward the request to a worker that has the action.
725+
// If forwardedWorker is truthy, it means there isn't a worker for the
726+
// action in the current handler, so we forward the request to a worker that
727+
// has the action.
715728
if (forwardedWorker) {
716729
return {
717730
type: 'done',
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { nextTestSetup } from 'e2e-utils'
2+
3+
describe('action forward loop prevention', () => {
4+
const { next } = nextTestSetup({
5+
files: __dirname,
6+
})
7+
8+
it('renders the action-not-found error when a rewrite sends the action POST to a route that does not bundle it', async () => {
9+
const browser = await next.browser('/with-action')
10+
await browser.elementById('run-action').click()
11+
await browser.waitForElementByCss('#action-not-found-error')
12+
})
13+
})
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { ReactNode } from 'react'
2+
export default function Root({ children }: { children: ReactNode }) {
3+
return (
4+
<html>
5+
<body>{children}</body>
6+
</html>
7+
)
8+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'use client'
2+
3+
import { Component, type ReactNode } from 'react'
4+
import { unstable_isUnrecognizedActionError } from 'next/navigation'
5+
6+
interface State {
7+
error: unknown
8+
}
9+
10+
export class ErrorBoundary extends Component<{ children: ReactNode }, State> {
11+
state: State = { error: null }
12+
13+
static getDerivedStateFromError(error: unknown): State {
14+
return { error }
15+
}
16+
17+
render() {
18+
const { error } = this.state
19+
if (error === null) {
20+
return this.props.children
21+
}
22+
if (unstable_isUnrecognizedActionError(error)) {
23+
return <p id="action-not-found-error">Server action not found</p>
24+
}
25+
return <p id="unexpected-error">Unexpected error</p>
26+
}
27+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { ErrorBoundary } from './error-boundary'
2+
3+
export default function Page() {
4+
return (
5+
<main>
6+
<h1 id="with-action-page">with-action</h1>
7+
<ErrorBoundary>
8+
<form
9+
action={async () => {
10+
'use server'
11+
}}
12+
>
13+
<button id="run-action">Run action</button>
14+
</form>
15+
</ErrorBoundary>
16+
</main>
17+
)
18+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export default function Page() {
2+
return <main>without-action</main>
3+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
/**
2+
* @type {import('next').NextConfig}
3+
*/
4+
const nextConfig = {}
5+
6+
module.exports = nextConfig
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { NextResponse } from 'next/server'
2+
import type { NextRequest } from 'next/server'
3+
4+
// Only rewrite action POSTs so the user can still GET the page to see the
5+
// button. The receiving worker is /without-action, which does not bundle the
6+
// action — so without the loop guard, the worker forwards the action back to
7+
// /with-action, which is rewritten here again, and so on.
8+
export function proxy(request: NextRequest) {
9+
if (
10+
request.method === 'POST' &&
11+
request.nextUrl.pathname === '/with-action'
12+
) {
13+
const url = request.nextUrl.clone()
14+
url.pathname = '/without-action'
15+
return NextResponse.rewrite(url)
16+
}
17+
return NextResponse.next()
18+
}
19+
20+
export const config = {
21+
matcher: '/with-action',
22+
}

0 commit comments

Comments
 (0)