Unverified Commit 6139f4b8 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

[backport] Fix server action forwarding loop with middleware rewrites (#93919)

Backports:

- #93792
Co-authored-by: 's avatarElisha Greenwald <ejgreenwald@gmail.com>
Co-authored-by: 's avatarLiamBoz <thisamazingnow@gmail.com>
Co-authored-by: 's avatarkmaclip <kmartclips@proton.me>
parent c021d10f
...@@ -278,9 +278,18 @@ async function createForwardedActionResponse( ...@@ -278,9 +278,18 @@ async function createForwardedActionResponse(
} }
return new FlightRenderResult(response.body!) return new FlightRenderResult(response.body!)
} else { }
// Since we aren't consuming the response body, we cancel it to avoid memory leaks
response.body?.cancel() // Since we aren't consuming the response body, we cancel it to avoid memory leaks
response.body?.cancel()
// Pass the action-not-found marker through so the client throws
// UnrecognizedActionError instead of a generic "unexpected response".
if (response.headers.get(NEXT_ACTION_NOT_FOUND_HEADER) === '1') {
res.setHeader(NEXT_ACTION_NOT_FOUND_HEADER, '1')
res.setHeader('content-type', 'text/plain')
res.statusCode = 404
return RenderResult.fromStatic('Server action not found.', 'text/plain')
} }
} catch (err) { } catch (err) {
// we couldn't stream the forwarded response, so we'll just return an empty response // we couldn't stream the forwarded response, so we'll just return an empty response
...@@ -707,11 +716,15 @@ export async function handleAction({ ...@@ -707,11 +716,15 @@ export async function handleAction({
const actionWasForwarded = Boolean(req.headers['x-action-forwarded']) const actionWasForwarded = Boolean(req.headers['x-action-forwarded'])
if (actionId) { // Only attempt to forward if this request has not already been forwarded.
// Otherwise middleware that rewrites the action POST can cause the receiving
// worker to forward again, looping indefinitely.
if (actionId && !actionWasForwarded) {
const forwardedWorker = selectWorkerForForwarding(actionId, page) const forwardedWorker = selectWorkerForForwarding(actionId, page)
// If forwardedWorker is truthy, it means there isn't a worker for the action // If forwardedWorker is truthy, it means there isn't a worker for the
// in the current handler, so we forward the request to a worker that has the action. // action in the current handler, so we forward the request to a worker that
// has the action.
if (forwardedWorker) { if (forwardedWorker) {
return { return {
type: 'done', type: 'done',
......
import { nextTestSetup } from 'e2e-utils'
describe('action forward loop prevention', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('renders the action-not-found error when a rewrite sends the action POST to a route that does not bundle it', async () => {
const browser = await next.browser('/with-action')
await browser.elementById('run-action').click()
await browser.waitForElementByCss('#action-not-found-error')
})
})
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import { Component, type ReactNode } from 'react'
import { unstable_isUnrecognizedActionError } from 'next/navigation'
interface State {
error: unknown
}
export class ErrorBoundary extends Component<{ children: ReactNode }, State> {
state: State = { error: null }
static getDerivedStateFromError(error: unknown): State {
return { error }
}
render() {
const { error } = this.state
if (error === null) {
return this.props.children
}
if (unstable_isUnrecognizedActionError(error)) {
return <p id="action-not-found-error">Server action not found</p>
}
return <p id="unexpected-error">Unexpected error</p>
}
}
import { ErrorBoundary } from './error-boundary'
export default function Page() {
return (
<main>
<h1 id="with-action-page">with-action</h1>
<ErrorBoundary>
<form
action={async () => {
'use server'
}}
>
<button id="run-action">Run action</button>
</form>
</ErrorBoundary>
</main>
)
}
export default function Page() {
return <main>without-action</main>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// Only rewrite action POSTs so the user can still GET the page to see the
// button. The receiving worker is /without-action, which does not bundle the
// action — so without the loop guard, the worker forwards the action back to
// /with-action, which is rewritten here again, and so on.
export function proxy(request: NextRequest) {
if (
request.method === 'POST' &&
request.nextUrl.pathname === '/with-action'
) {
const url = request.nextUrl.clone()
url.pathname = '/without-action'
return NextResponse.rewrite(url)
}
return NextResponse.next()
}
export const config = {
matcher: '/with-action',
}
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