Commit 1d73eb9f authored by Jonas Herrmannsdörfer's avatar Jonas Herrmannsdörfer Committed by Tobias Koppers

fix: trigger MPA navigation for server action redirects with build ID mismatch (#89946)

## Summary

- Fixes cross-zone server action redirect failure where `redirect()`
inside a server action produces a blank page when the target path is
served by a different Next.js zone (separate Vercel project, same
domain)
- Adds build ID validation to `server-action-reducer.ts`, matching the
existing pattern in `fetch-server-response.ts`
- Adds e2e test in the deployment-skew test suite to verify server
action redirects with build ID mismatch trigger MPA navigation

## Background

When a server action calls `redirect()`, the server pre-fetches the
redirect target and includes the RSC data in the response. In a
multi-zone setup (same domain, different Next.js projects), this
pre-fetched RSC data comes from a different build with a different build
ID.

The `fetch-server-response.ts` file already checks for build ID
mismatches during regular navigations (line 245-251) and triggers MPA
navigation when detected. However, `server-action-reducer.ts` was
missing this check, causing the client to try to apply the foreign RSC
payload — resulting in a blank page.

## Fix

Added a build ID check in `fetchServerAction()` after parsing the RSC
response. When a mismatch is detected, the flight data is discarded. The
existing reducer logic at line 364-370 already handles this case:

```typescript
if (flightData === undefined && redirectLocation !== undefined) {
  return completeHardNavigation(state, redirectLocation, navigateType)
}
```

This triggers an MPA navigation (full page load), which is the correct
behavior for cross-zone redirects.

## Repro

- https://repro-main-app.vercel.app/test-redirect
- Red button (server action redirect) → blank page (before fix) / full
page load (after fix)
  - Green link (normal `<a>`) → works fine

Closes https://linear.app/vercel/issue/NEXT-4856

---------
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
parent e9891cf4
...@@ -1251,7 +1251,9 @@ export async function handler( ...@@ -1251,7 +1251,9 @@ export async function handler(
// Set the build ID header for RSC navigation requests when deploymentId is configured. This // Set the build ID header for RSC navigation requests when deploymentId is configured. This
// corresponds with maybeAppendBuildIdToRSCPayload in app-render.tsx which omits the build ID // corresponds with maybeAppendBuildIdToRSCPayload in app-render.tsx which omits the build ID
// from the RSC payload when deploymentId is set (relying on this header instead). Server // from the RSC payload when deploymentId is set (relying on this header instead). Server
// actions are excluded because the client doesn't check the build ID for action responses. // actions are excluded here because action redirect responses get the deployment ID header
// from the pre-fetched redirect target (via createRedirectRenderResult in action-handler.ts
// which copies headers from the internal RSC fetch).
// For static prerenders served from CDN, routes-manifest.json adds a header. // For static prerenders served from CDN, routes-manifest.json adds a header.
if (isRSCRequest && !isPossibleServerAction && deploymentId) { if (isRSCRequest && !isPossibleServerAction && deploymentId) {
res.setHeader(NEXT_NAV_DEPLOYMENT_ID_HEADER, deploymentId) res.setHeader(NEXT_NAV_DEPLOYMENT_ID_HEADER, deploymentId)
......
...@@ -48,6 +48,8 @@ import { ...@@ -48,6 +48,8 @@ import {
import { invalidateEntirePrefetchCache } from '../../segment-cache/cache' import { invalidateEntirePrefetchCache } from '../../segment-cache/cache'
import { startRevalidationCooldown } from '../../segment-cache/scheduler' import { startRevalidationCooldown } from '../../segment-cache/scheduler'
import { getDeploymentId } from '../../../../shared/lib/deployment-id' import { getDeploymentId } from '../../../../shared/lib/deployment-id'
import { getNavigationBuildId } from '../../../navigation-build-id'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../../lib/constants'
import { import {
completeHardNavigation, completeHardNavigation,
convertServerPatchToFullTree, convertServerPatchToFullTree,
...@@ -226,10 +228,30 @@ async function fetchServerAction( ...@@ -226,10 +228,30 @@ async function fetchServerAction(
// An internal redirect can send an RSC response, but does not have a useful `actionResult`. // An internal redirect can send an RSC response, but does not have a useful `actionResult`.
actionResult = redirectLocation ? undefined : response.a actionResult = redirectLocation ? undefined : response.a
couldBeIntercepted = response.i couldBeIntercepted = response.i
const maybeFlightData = normalizeFlightData(response.f)
if (maybeFlightData !== '') { // Check if the response build ID matches the client build ID.
actionFlightData = maybeFlightData // In a multi-zone setup, when a server action triggers a redirect,
actionFlightDataRenderedSearch = response.q as NormalizedSearch // the server pre-fetches the redirect target as RSC. If the redirect
// target is served by a different Next.js zone (different build), the
// pre-fetched RSC data will have a foreign build ID. We must discard
// the flight data in that case so the redirect triggers an MPA
// navigation (full page load) instead of trying to apply the foreign
// RSC payload — which would result in a blank page.
const responseBuildId =
res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? response.b
if (
responseBuildId !== undefined &&
responseBuildId !== getNavigationBuildId()
) {
// Build ID mismatch — discard the flight data. The redirect will
// still be processed, and the absence of flight data will cause an
// MPA navigation via completeHardNavigation().
} else {
const maybeFlightData = normalizeFlightData(response.f)
if (maybeFlightData !== '') {
actionFlightData = maybeFlightData
actionFlightDataRenderedSearch = response.q as NormalizedSearch
}
} }
} else { } else {
// An external redirect doesn't contain RSC data. // An external redirect doesn't contain RSC data.
......
import { redirect } from 'next/navigation'
async function redirectToOtherDeployment() {
'use server'
// Route the redirect prefetch back through the test proxy so the action
// response can come from deployment 2 instead of the current worker.
if (process.env.TEST_PROXY_ORIGIN) {
process.env.__NEXT_PRIVATE_ORIGIN = process.env.TEST_PROXY_ORIGIN
}
redirect('/dynamic-page?deployment=2')
}
export default function ActionRedirectPage() {
return (
<div>
<h1 id="action-page">Action Redirect Page</h1>
<form action={redirectToOtherDeployment}>
<button id="redirect-action-button" type="submit">
Redirect via Server Action
</button>
</form>
</div>
)
}
'use client'
import { redirectToOtherDeployment } from './redirect-action'
export function ActionRedirectButton() {
return (
<form action={redirectToOtherDeployment}>
<button id="redirect-action-button" type="submit">
Redirect via Server Action
</button>
</form>
)
}
'use server'
import { redirect } from 'next/navigation'
export async function redirectToOtherDeployment() {
// Redirect to the dynamic page on deployment 2
redirect('/dynamic-page?deployment=2')
}
import type * as Playwright from 'playwright' import type * as Playwright from 'playwright'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
import { findPort } from 'next-test-utils' import { findPort, retry } from 'next-test-utils'
import { isNextDeploy, isNextDev, isNextStart, nextTestSetup } from 'e2e-utils' import { isNextDeploy, isNextDev, isNextStart, nextTestSetup } from 'e2e-utils'
import { build, start } from './servers.mjs' import { build, start } from './servers.mjs'
...@@ -38,7 +38,7 @@ describe('segment cache (deployment skew)', () => { ...@@ -38,7 +38,7 @@ describe('segment cache (deployment skew)', () => {
await cleanup() await cleanup()
}) })
runTests(() => port) runTests('BUILD_ID', () => port)
}) })
describe('with NEXT_DEPLOYMENT_ID', () => { describe('with NEXT_DEPLOYMENT_ID', () => {
...@@ -54,7 +54,7 @@ describe('segment cache (deployment skew)', () => { ...@@ -54,7 +54,7 @@ describe('segment cache (deployment skew)', () => {
await cleanup() await cleanup()
}) })
runTests(() => port) runTests('DEPLOYMENT_ID', () => port)
}) })
} }
...@@ -84,7 +84,7 @@ describe('segment cache (deployment skew)', () => { ...@@ -84,7 +84,7 @@ describe('segment cache (deployment skew)', () => {
}) })
}) })
function runTests(getPort: () => number) { function runTests(mode: 'BUILD_ID' | 'DEPLOYMENT_ID', getPort: () => number) {
it( it(
'does not crash when prefetching a dynamic, non-PPR page ' + 'does not crash when prefetching a dynamic, non-PPR page ' +
'on a different deployment', 'on a different deployment',
...@@ -151,4 +151,74 @@ function runTests(getPort: () => number) { ...@@ -151,4 +151,74 @@ function runTests(getPort: () => number) {
}, },
60 * 1000 60 * 1000
) )
it(
'triggers MPA navigation when a server action redirects to a different deployment',
async () => {
// Verify that when a server action calls redirect() and the redirect
// target is served by a different deployment (different build ID), the
// client falls back to an MPA navigation instead of attempting to apply
// the foreign RSC payload.
const browser = await webdriver(getPort(), '/')
await browser.eval('window.next.router.push("/action-redirect")')
await browser.waitForElementByCss('#action-page')
let sawActionRequest = false
let sawRedirectActionResponse = false
let actionResponseDeploymentId: string | undefined
browser.on('request', (request: Playwright.Request) => {
const headers = request.headers()
if (request.method() === 'POST' && headers['next-action']) {
sawActionRequest = true
}
})
browser.on('response', async (response: Playwright.Response) => {
const request = response.request()
if (request.method() !== 'POST') {
return
}
const headers = response.headers()
if (headers['x-action-redirect']) {
sawRedirectActionResponse = true
actionResponseDeploymentId = headers['x-nextjs-deployment-id']
}
})
// Verify we're on the action redirect page
const heading = await browser.elementById('action-page')
expect(await heading.text()).toBe('Action Redirect Page')
// Click the button that triggers the server action redirect.
// In deployment ID mode, the proxy injects a foreign
// x-nextjs-deployment-id header to simulate skew. In build ID mode,
// the response omits that header so the client falls back to the
// build ID carried in the action Flight payload.
const button = await browser.elementById('redirect-action-button')
await button.click()
await retry(async () => {
expect(sawActionRequest).toBe(true)
})
await retry(async () => {
expect(sawRedirectActionResponse).toBe(true)
})
if (mode === 'DEPLOYMENT_ID') {
expect(actionResponseDeploymentId).toBe('foreign-deployment')
} else {
expect(actionResponseDeploymentId).toBeUndefined()
}
// Wait for the navigation to complete.
// The client detects the mismatch in either the response header or
// the fallback build ID field and discards the flight data,
// triggering an MPA navigation (full page load) to the redirect
// target. The redirect URL (/dynamic-page?deployment=2) goes through
// the proxy to deployment 2.
const buildId = await browser.waitForElementByCss('#build-id')
expect(await buildId.text()).toBe('Build ID: 2')
},
60 * 1000
)
} }
...@@ -8,16 +8,23 @@ import process from 'node:process' ...@@ -8,16 +8,23 @@ import process from 'node:process'
const dir = dirname(fileURLToPath(import.meta.url)) const dir = dirname(fileURLToPath(import.meta.url))
function getEnv(id, mode) { function getEnv(id, mode) {
const base = {
...process.env,
DIST_DIR: id,
// Required so the build includes the __NEXT_HYDRATED callback used by
// webdriver() to detect hydration. Without this, the hydration check
// always times out and tests may interact with the page before the
// React app router is initialized.
__NEXT_TEST_MODE: 'e2e',
}
if (mode === 'BUILD_ID') { if (mode === 'BUILD_ID') {
return { return {
...process.env, ...base,
DIST_DIR: id,
NEXT_PUBLIC_BUILD_ID: id, NEXT_PUBLIC_BUILD_ID: id,
} }
} else if (mode === 'DEPLOYMENT_ID') { } else if (mode === 'DEPLOYMENT_ID') {
return { return {
...process.env, ...base,
DIST_DIR: id,
NEXT_DEPLOYMENT_ID: id, NEXT_DEPLOYMENT_ID: id,
} }
} else { } else {
...@@ -25,9 +32,12 @@ function getEnv(id, mode) { ...@@ -25,9 +32,12 @@ function getEnv(id, mode) {
} }
} }
async function spawnNext(id, mode, port) { async function spawnNext(id, mode, port, extraEnv = {}) {
const child = spawn('pnpm', ['next', 'start', '-p', port, dir], { const child = spawn('pnpm', ['next', 'start', '-p', port, dir], {
env: getEnv(id, mode), env: {
...getEnv(id, mode),
...extraEnv,
},
stdio: ['inherit', 'pipe', 'inherit'], stdio: ['inherit', 'pipe', 'inherit'],
}) })
...@@ -68,16 +78,32 @@ export async function start( ...@@ -68,16 +78,32 @@ export async function start(
nextPort2 = mainPort + 2, nextPort2 = mainPort + 2,
mode = 'BUILD_ID' mode = 'BUILD_ID'
) { ) {
const extraEnv = {
TEST_PROXY_ORIGIN: `http://localhost:${mainPort}`,
}
// Start two different Next.js servers, one with BUILD_ID=1 and one // Start two different Next.js servers, one with BUILD_ID=1 and one
// with BUILD_ID=2 // with BUILD_ID=2
const [next1, next2] = await Promise.all([ const [next1, next2] = await Promise.all([
spawnNext('1', mode, nextPort1), spawnNext('1', mode, nextPort1, extraEnv),
spawnNext('2', mode, nextPort2), spawnNext('2', mode, nextPort2, extraEnv),
]) ])
// Create a proxy server. If search params include `deployment=2`, proxy to // Create a proxy server. If search params include `deployment=2`, proxy to
// to the second next server. Otherwise, proxy to the first. // to the second next server. Otherwise, proxy to the first.
const proxy = httpProxy.createProxyServer() const proxy = httpProxy.createProxyServer()
// Simulate deployment skew for deployment ID-based action responses. When a
// POST (server action) is handled by deployment 1, inject a foreign
// x-nextjs-deployment-id header so the client detects a mismatch and
// triggers an MPA navigation. BUILD_ID mode intentionally skips this so the
// test exercises the response.b fallback instead.
proxy.on('proxyRes', (proxyRes, req) => {
if (mode === 'DEPLOYMENT_ID' && req.method === 'POST') {
proxyRes.headers['x-nextjs-deployment-id'] = 'foreign-deployment'
}
})
const server = createServer((req, res) => { const server = createServer((req, res) => {
let port = nextPort1 let port = nextPort1
if (req.url) { if (req.url) {
......
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