Unverified Commit c116da32 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

fix double redirect when using a loading boundary (#63786)

### What & Why
When an RSC triggers `navigate` after the shell has already been sent to
the client, a meta tag is inserted to signal to the browser it needs to
perform an MPA navigation. This is primarily used for bot user agents,
since we wouldn't have been able to provide a proper redirect status
code (since it occurred after the initial response was sent).

However, the router would trigger a SPA navigation, while the `<meta>`
tag lagged to perform an MPA navigation, resulting in 2 navigations to
the same URL.

### How
When the client side code attempts to handle the redirect, we treat it
like an MPA navigation. This will suspend in render and trigger a
`location.push`/`location.replace` to the targeted URL. As a result,
only one of these navigation events will win.

Fixes #59800
Fixes #62463

Closes NEXT-2952
Closes NEXT-2719
parent ae61e7e0
import type { FlightRouterState } from '../../../server/app-render/types' import type { FlightRouterState } from '../../../server/app-render/types'
import { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout' import { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout'
describe('shouldHardNavigate', () => { describe('isNavigatingToNewRootLayout', () => {
it('should return false if there is no new root layout', () => { it('should return false if there is no new root layout', () => {
const getInitialRouterStateTree = (): FlightRouterState => [ const getInitialRouterStateTree = (): FlightRouterState => [
'', '',
......
...@@ -150,6 +150,12 @@ function navigateReducer_noPPR( ...@@ -150,6 +150,12 @@ function navigateReducer_noPPR(
return handleExternalUrl(state, mutable, flightData, pendingPush) return handleExternalUrl(state, mutable, flightData, pendingPush)
} }
// Handles case where `<meta http-equiv="refresh">` tag is present,
// which will trigger an MPA navigation.
if (document.getElementById('__next-page-redirect')) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
let currentTree = state.tree let currentTree = state.tree
const currentCache = state.cache const currentCache = state.cache
let scrollableSegments: FlightSegmentPath[] = [] let scrollableSegments: FlightSegmentPath[] = []
...@@ -318,6 +324,12 @@ function navigateReducer_PPR( ...@@ -318,6 +324,12 @@ function navigateReducer_PPR(
return handleExternalUrl(state, mutable, flightData, pendingPush) return handleExternalUrl(state, mutable, flightData, pendingPush)
} }
// Handles case where `<meta http-equiv="refresh">` tag is present,
// which will trigger an MPA navigation.
if (document.getElementById('__next-page-redirect')) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
let currentTree = state.tree let currentTree = state.tree
const currentCache = state.cache const currentCache = state.cache
let scrollableSegments: FlightSegmentPath[] = [] let scrollableSegments: FlightSegmentPath[] = []
......
...@@ -50,6 +50,7 @@ export function makeGetServerInsertedHTML({ ...@@ -50,6 +50,7 @@ export function makeGetServerInsertedHTML({
if (redirectUrl) { if (redirectUrl) {
errorMetaTags.push( errorMetaTags.push(
<meta <meta
id="__next-page-redirect"
httpEquiv="refresh" httpEquiv="refresh"
content={`${isPermanent ? 0 : 1};url=${redirectUrl}`} content={`${isPermanent ? 0 : 1};url=${redirectUrl}`}
key={error.digest} key={error.digest}
......
export default function Loading() {
return <div id="loading">Loading...</div>
}
import { redirect } from 'next/navigation'
export default async function Page() {
// fake delay 1s to trigger loading state
await new Promise((res) => setTimeout(res, 1000))
redirect('/redirect/result')
}
export default function Page() { export default function Page() {
return <h1 id="result-page">Result Page</h1> return (
<div>
<h1 id="result-page">Result Page</h1>
<div id="timestamp">{Date.now()}</div>
</div>
)
} }
...@@ -457,6 +457,47 @@ createNextDescribe( ...@@ -457,6 +457,47 @@ createNextDescribe(
isNextDev ? ['1', '2'] : ['1'] isNextDev ? ['1', '2'] : ['1']
) )
}) })
it.each([
'/redirect/servercomponent',
'redirect/redirect-with-loading',
])('should only trigger the redirect once (%s)', async (path) => {
const browser = await next.browser(path)
const initialTimestamp = await browser
.waitForElementByCss('#timestamp')
.text()
let attempts = 0
const maxAttempts = 5
try {
// this ensures the timestamp remains "stable" (ie, we didn't trigger another redirect)
await retry(async () => {
const currentTimestamp = await browser
.elementByCss('#timestamp')
.text()
attempts++
// If the timestamp has changed, throw immediately.
if (currentTimestamp !== initialTimestamp) {
throw new Error('Timestamp has changed')
}
// If we've reached the last attempt without the timestamp changing, force a retry failure to keep going.
if (attempts < maxAttempts) {
throw new Error('Forcing continue')
}
})
} catch (err) {
// If we catch the "Forcing continue" error, it means our condition held until the end.
// If it's a different error (i.e., the timestamp changed), we rethrow it.
if (err.message !== 'Forcing continue') {
throw err // Rethrow if the error is not our "force continue" error.
}
// If it's our "forcing continue" error, do nothing. This means we succeeded.
}
})
}) })
describe('next.config.js redirects', () => { describe('next.config.js redirects', () => {
...@@ -700,14 +741,14 @@ createNextDescribe( ...@@ -700,14 +741,14 @@ createNextDescribe(
it('should emit refresh meta tag for redirect page when streaming', async () => { it('should emit refresh meta tag for redirect page when streaming', async () => {
const html = await next.render('/redirect/suspense') const html = await next.render('/redirect/suspense')
expect(html).toContain( expect(html).toContain(
'<meta http-equiv="refresh" content="1;url=/redirect/result"/>' '<meta id="__next-page-redirect" http-equiv="refresh" content="1;url=/redirect/result"/>'
) )
}) })
it('should emit refresh meta tag (permanent) for redirect page when streaming', async () => { it('should emit refresh meta tag (permanent) for redirect page when streaming', async () => {
const html = await next.render('/redirect/suspense-2') const html = await next.render('/redirect/suspense-2')
expect(html).toContain( expect(html).toContain(
'<meta http-equiv="refresh" content="0;url=/redirect/result"/>' '<meta id="__next-page-redirect" http-equiv="refresh" content="0;url=/redirect/result"/>'
) )
}) })
......
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