Unverified Commit 2c80a0f5 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

update redirect handling on forwarded action requests (#65097)

If a forwarded server action redirects, don't attempt to follow the
redirect as it can lead to errors. For example, if the forwarded request
followed a redirect to the same URL and had to forward the request
again, it'd hit a loop. The redirect will be handled by the
`X-Action-Redirect` which will be set when the forwarded action hits the
`createRedirectRenderResult` case.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Closes NEXT-3243
parent fa9f684e
...@@ -206,6 +206,7 @@ async function createForwardedActionResponse( ...@@ -206,6 +206,7 @@ async function createForwardedActionResponse(
body, body,
duplex: 'half', duplex: 'half',
headers: forwardedHeaders, headers: forwardedHeaders,
redirect: 'manual',
next: { next: {
// @ts-ignore // @ts-ignore
internal: 1, internal: 1,
...@@ -226,9 +227,11 @@ async function createForwardedActionResponse( ...@@ -226,9 +227,11 @@ async function createForwardedActionResponse(
response.body?.cancel() response.body?.cancel()
} }
} catch (err) { } catch (err) {
// we couldn't stream the forwarded response, so we'll just do a normal redirect // we couldn't stream the forwarded response, so we'll just return an empty response
console.error(`failed to forward action response`, err) console.error(`failed to forward action response`, err)
} }
return RenderResult.fromStatic('{}')
} }
async function createRedirectRenderResult( async function createRedirectRenderResult(
......
...@@ -598,6 +598,40 @@ describe('app-dir action handling', () => { ...@@ -598,6 +598,40 @@ describe('app-dir action handling', () => {
} }
) )
it.each(['node', 'edge'])(
'should not error when a forwarded action triggers a redirect (%s)',
async (runtime) => {
let redirectResponseCode
const browser = await next.browser(`/delayed-action/${runtime}`, {
beforePageLoad(page) {
page.on('response', async (res: Response) => {
const headers = await res.allHeaders()
if (headers['x-action-redirect']) {
redirectResponseCode = res.status()
}
})
},
})
// Trigger the delayed action. This will sleep for a few seconds before dispatching the server action handler
await browser.elementById('run-action-redirect').click()
// navigate away from the page
await browser
.elementByCss(`[href='/delayed-action/${runtime}/other']`)
.click()
.waitForElementByCss('#other-page')
// confirm a successful response code on the redirected action
await retry(async () => {
expect(redirectResponseCode).toBe(200)
})
// confirm that the redirect was handled
await browser.waitForElementByCss('#run-action-redirect')
}
)
if (isNextStart) { if (isNextStart) {
it('should not expose action content in sourcemaps', async () => { it('should not expose action content in sourcemaps', async () => {
const sourcemap = ( const sourcemap = (
......
'use server' 'use server'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
export const action = async () => { export const action = async () => {
console.log('revalidating') console.log('revalidating')
revalidatePath('/delayed-action', 'page') revalidatePath('/delayed-action', 'page')
return Math.random() return Math.random()
} }
export const redirectAction = async () => {
// sleep for 500ms
await new Promise((res) => setTimeout(res, 500))
redirect('/delayed-action/node')
}
'use client' 'use client'
import { useContext } from 'react' import { useContext } from 'react'
import { action } from './actions' import { action, redirectAction } from './actions'
import { DataContext } from './context' import { DataContext } from './context'
export function Button() { export function Button() {
...@@ -13,9 +13,24 @@ export function Button() { ...@@ -13,9 +13,24 @@ export function Button() {
setData(result) setData(result)
} }
const handleRedirect = async () => {
await new Promise((res) => setTimeout(res, 1000))
const result = await redirectAction()
setData(result)
}
return ( return (
<button onClick={handleClick} id="run-action"> <>
Run Action <button onClick={handleClick} id="run-action">
</button> Run Action
</button>
<button onClick={handleRedirect} id="run-action-redirect">
Run Redirect
</button>
</>
) )
} }
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