Skip to content

Commit

Permalink
update redirect handling on forwarded action requests (#65097)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
ztanner committed Apr 26, 2024
1 parent fa9f684 commit 2c80a0f
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 5 deletions.
5 changes: 4 additions & 1 deletion packages/next/src/server/app-render/action-handler.ts
Expand Up @@ -206,6 +206,7 @@ async function createForwardedActionResponse(
body,
duplex: 'half',
headers: forwardedHeaders,
redirect: 'manual',
next: {
// @ts-ignore
internal: 1,
Expand All @@ -226,9 +227,11 @@ async function createForwardedActionResponse(
response.body?.cancel()
}
} 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)
}

return RenderResult.fromStatic('{}')
}

async function createRedirectRenderResult(
Expand Down
34 changes: 34 additions & 0 deletions test/e2e/app-dir/actions/app-action.test.ts
Expand Up @@ -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) {
it('should not expose action content in sourcemaps', async () => {
const sourcemap = (
Expand Down
7 changes: 7 additions & 0 deletions test/e2e/app-dir/actions/app/delayed-action/actions.ts
@@ -1,8 +1,15 @@
'use server'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'

export const action = async () => {
console.log('revalidating')
revalidatePath('/delayed-action', 'page')
return Math.random()
}

export const redirectAction = async () => {
// sleep for 500ms
await new Promise((res) => setTimeout(res, 500))
redirect('/delayed-action/node')
}
23 changes: 19 additions & 4 deletions test/e2e/app-dir/actions/app/delayed-action/button.tsx
@@ -1,7 +1,7 @@
'use client'

import { useContext } from 'react'
import { action } from './actions'
import { action, redirectAction } from './actions'
import { DataContext } from './context'

export function Button() {
Expand All @@ -13,9 +13,24 @@ export function Button() {

setData(result)
}

const handleRedirect = async () => {
await new Promise((res) => setTimeout(res, 1000))

const result = await redirectAction()

setData(result)
}

return (
<button onClick={handleClick} id="run-action">
Run Action
</button>
<>
<button onClick={handleClick} id="run-action">
Run Action
</button>

<button onClick={handleRedirect} id="run-action-redirect">
Run Redirect
</button>
</>
)
}

0 comments on commit 2c80a0f

Please sign in to comment.