Unverified Commit 363c2e8e authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

fix server actions behavior on intercepted routes (#59175)

### What?
When using a server action on an intercepted route, when submitting that
action, you'd expect it to correspond with the page you're currently on.
However if you have route interception set up, and you load the page
rather than the intercepted page, submitting the action would `POST` to
the intercepted page. This would result in a 404 error because the
action ID you're attempting to submit wouldn't be found on the requested
page.

### Why?
Interception routes rely on the `Next-Url` request header to determine
if an interception should occur via a rewrite. However, server actions
are submitted with this header as well, so the rewrite will be applied
to the `POST` request corresponding with a non-existent action, or an
action on the intercepted page.

### How?
When loading a page that has an intercepted route, `nextUrl` should be
consistent with URL derived from the flight router state tree. But when
an interception occurs via navigation, `nextUrl` will now deviate. I'm
using this to determine whether or not `Next-Url` should be forwarded
along in the `POST` request.

Closes NEXT-1436
Fixes #52591
Fixes #49934
parent 840b60bc
...@@ -39,6 +39,7 @@ import { ...@@ -39,6 +39,7 @@ import {
import { handleMutable } from '../handle-mutable' import { handleMutable } from '../handle-mutable'
import { fillLazyItemsTillLeafWithHead } from '../fill-lazy-items-till-leaf-with-head' import { fillLazyItemsTillLeafWithHead } from '../fill-lazy-items-till-leaf-with-head'
import { createEmptyCacheNode } from '../../app-router' import { createEmptyCacheNode } from '../../app-router'
import { extractPathFromFlightRouterState } from '../compute-changed-path'
type FetchServerActionResult = { type FetchServerActionResult = {
redirectLocation: URL | undefined redirectLocation: URL | undefined
...@@ -57,6 +58,13 @@ async function fetchServerAction( ...@@ -57,6 +58,13 @@ async function fetchServerAction(
): Promise<FetchServerActionResult> { ): Promise<FetchServerActionResult> {
const body = await encodeReply(actionArgs) const body = await encodeReply(actionArgs)
const newNextUrl = extractPathFromFlightRouterState(state.tree)
// only pass along the `nextUrl` param (used for interception routes) if it exists and
// if it's different from the current `nextUrl`. This indicates the route has already been intercepted,
// and so the action should be as well. Otherwise the server action might be intercepted
// with the wrong action id (ie, one that corresponds with the intercepted route)
const includeNextUrl = state.nextUrl && state.nextUrl !== newNextUrl
const res = await fetch('', { const res = await fetch('', {
method: 'POST', method: 'POST',
headers: { headers: {
...@@ -69,7 +77,7 @@ async function fetchServerAction( ...@@ -69,7 +77,7 @@ async function fetchServerAction(
'x-deployment-id': process.env.NEXT_DEPLOYMENT_ID, 'x-deployment-id': process.env.NEXT_DEPLOYMENT_ID,
} }
: {}), : {}),
...(state.nextUrl ...(includeNextUrl
? { ? {
[NEXT_URL]: state.nextUrl, [NEXT_URL]: state.nextUrl,
} }
......
...@@ -14,7 +14,7 @@ import fs from 'fs/promises' ...@@ -14,7 +14,7 @@ import fs from 'fs/promises'
import * as Log from '../../../build/output/log' import * as Log from '../../../build/output/log'
import setupDebug from 'next/dist/compiled/debug' import setupDebug from 'next/dist/compiled/debug'
import LRUCache from 'next/dist/compiled/lru-cache' import LRUCache from 'next/dist/compiled/lru-cache'
import loadCustomRoutes from '../../../lib/load-custom-routes' import loadCustomRoutes, { type Rewrite } from '../../../lib/load-custom-routes'
import { modifyRouteRegex } from '../../../lib/redirect-status' import { modifyRouteRegex } from '../../../lib/redirect-status'
import { FileType, fileExists } from '../../../lib/file-exists' import { FileType, fileExists } from '../../../lib/file-exists'
import { recursiveReadDir } from '../../../lib/recursive-readdir' import { recursiveReadDir } from '../../../lib/recursive-readdir'
...@@ -395,7 +395,7 @@ export async function setupFsCheck(opts: { ...@@ -395,7 +395,7 @@ export async function setupFsCheck(opts: {
interceptionRoutes: undefined as interceptionRoutes: undefined as
| undefined | undefined
| ReturnType<typeof buildCustomRoute>[], | ReturnType<typeof buildCustomRoute<Rewrite>>[],
devVirtualFsItems: new Set<string>(), devVirtualFsItems: new Set<string>(),
......
...@@ -929,6 +929,46 @@ createNextDescribe( ...@@ -929,6 +929,46 @@ createNextDescribe(
) )
}) })
it('should work with interception routes', async () => {
const browser = await next.browser('/interception-routes')
await check(
() => browser.elementById('children-data').text(),
/Open modal/
)
await browser.elementByCss("[href='/interception-routes/test']").click()
// verify the URL is correct
await check(() => browser.url(), /interception-routes\/test/)
// the intercepted text should appear
await check(() => browser.elementById('modal-data').text(), /in "modal"/)
// Submit the action
await browser.elementById('submit-intercept-action').click()
// Action log should be in server console
await check(() => next.cliOutput, /Action Submitted \(Intercepted\)/)
await browser.refresh()
// the modal text should be gone
expect(await browser.hasElementByCssSelector('#modal-data')).toBeFalsy()
// The page text should show
await check(
() => browser.elementById('children-data').text(),
/in "page"/
)
// Submit the action
await browser.elementById('submit-page-action').click()
// Action log should be in server console
await check(() => next.cliOutput, /Action Submitted \(Page\)/)
})
describe('encryption', () => { describe('encryption', () => {
it('should send encrypted values from the closed over closure', async () => { it('should send encrypted values from the closed over closure', async () => {
const res = await next.fetch('/encryption') const res = await next.fetch('/encryption')
......
export default function TestPageIntercepted() {
async function action(data) {
'use server'
console.log('Action Submitted (Intercepted)')
}
return (
<form action={action}>
in "modal"
<button type="submit" id="submit-intercept-action">
Test
</button>
</form>
)
}
export default function Layout({ children, modal }) {
return (
<>
<div id="modal-data">{modal}</div>
<div id="children-data">{children}</div>
</>
)
}
import Link from 'next/link'
export default function InterceptedPage() {
return <Link href="/interception-routes/test">Open modal</Link>
}
export default function TestPage() {
async function action(data) {
'use server'
console.log('Action Submitted (Page)')
}
return (
<form action={action} id="children-data">
in "page"
<button type="submit" id="submit-page-action">
Test
</button>
</form>
)
}
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