Commit 6aee03de authored by Zack Tanner's avatar Zack Tanner

fix router crash on revalidate + popstate (#62383)

When the popstate action is fired (as is the case in a browser back
button), if the page you're going back to has missing cache node data,
the router will crash.

Almost all router actions will suspend at the app-router level with the
exception of `ACTION_RESTORE`. This was to address an issue where
suspending in the router would add enough delay for browser scroll
restoration behavior not to work.

As a result, when going back to the page with missing data, app-router
wouldn't suspend but layout-router would suspend on the missing data
while triggering a lazy fetch. We trigger a server-patch with the
applied lazy data, but when React replays the render, it will replay the
branch without the cache node data applied. This results in the router
getting caught in a loop of suspending, applying the cache node,
replaying the branch without the cache node, and eventually crashing due
to an error thrown by React to prevent re-suspending indefinitely.

This adds a property to the cache node to signal if the lazy data has
been resolved. If it has been, we won't call the server patch action
again.

Fixes #61336
Closes NEXT-2438
parent 8fd3d7ee
...@@ -153,6 +153,7 @@ export function createEmptyCacheNode(): CacheNode { ...@@ -153,6 +153,7 @@ export function createEmptyCacheNode(): CacheNode {
rsc: null, rsc: null,
prefetchRsc: null, prefetchRsc: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
lazyDataResolved: false,
} }
} }
...@@ -541,7 +542,6 @@ function Router({ ...@@ -541,7 +542,6 @@ function Router({
return return
} }
// @ts-ignore useTransition exists
// TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously // TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously
// Without startTransition works if the cache is there for this path // Without startTransition works if the cache is there for this path
startTransition(() => { startTransition(() => {
......
...@@ -355,6 +355,7 @@ function InnerLayoutRouter({ ...@@ -355,6 +355,7 @@ function InnerLayoutRouter({
prefetchRsc: null, prefetchRsc: null,
head: null, head: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
lazyDataResolved: false,
} }
/** /**
...@@ -411,6 +412,7 @@ function InnerLayoutRouter({ ...@@ -411,6 +412,7 @@ function InnerLayoutRouter({
context.nextUrl, context.nextUrl,
buildId buildId
) )
childNode.lazyDataResolved = false
} }
/** /**
...@@ -419,12 +421,19 @@ function InnerLayoutRouter({ ...@@ -419,12 +421,19 @@ function InnerLayoutRouter({
// When the data has not resolved yet `use` will suspend here. // When the data has not resolved yet `use` will suspend here.
const [flightData, overrideCanonicalUrl] = use(lazyData) const [flightData, overrideCanonicalUrl] = use(lazyData)
// setTimeout is used to start a new transition during render, this is an intentional hack around React. if (!childNode.lazyDataResolved) {
setTimeout(() => { // setTimeout is used to start a new transition during render, this is an intentional hack around React.
startTransition(() => { setTimeout(() => {
changeByServerResponse(fullTree, flightData, overrideCanonicalUrl) startTransition(() => {
changeByServerResponse(fullTree, flightData, overrideCanonicalUrl)
})
}) })
})
// It's important that we mark this as resolved, in case this branch is replayed, we don't want to continously re-apply
// the patch to the tree.
childNode.lazyDataResolved = true
}
// Suspend infinitely as `changeByServerResponse` will cause a different part of the tree to be rendered. // Suspend infinitely as `changeByServerResponse` will cause a different part of the tree to be rendered.
use(createInfinitePromise()) as never use(createInfinitePromise()) as never
} }
......
...@@ -183,6 +183,7 @@ describe('navigateReducer', () => { ...@@ -183,6 +183,7 @@ describe('navigateReducer', () => {
"buildId": "development", "buildId": "development",
"cache": { "cache": {
"lazyData": null, "lazyData": null,
"lazyDataResolved": false,
"parallelRoutes": Map { "parallelRoutes": Map {
"children" => Map { "children" => Map {
"linking" => { "linking" => {
...@@ -377,6 +378,7 @@ describe('navigateReducer', () => { ...@@ -377,6 +378,7 @@ describe('navigateReducer', () => {
"buildId": "development", "buildId": "development",
"cache": { "cache": {
"lazyData": null, "lazyData": null,
"lazyDataResolved": false,
"parallelRoutes": Map { "parallelRoutes": Map {
"children" => Map { "children" => Map {
"linking" => { "linking" => {
...@@ -1040,6 +1042,7 @@ describe('navigateReducer', () => { ...@@ -1040,6 +1042,7 @@ describe('navigateReducer', () => {
"buildId": "development", "buildId": "development",
"cache": { "cache": {
"lazyData": null, "lazyData": null,
"lazyDataResolved": false,
"parallelRoutes": Map { "parallelRoutes": Map {
"children" => Map { "children" => Map {
"linking" => { "linking" => {
...@@ -1278,6 +1281,7 @@ describe('navigateReducer', () => { ...@@ -1278,6 +1281,7 @@ describe('navigateReducer', () => {
"buildId": "development", "buildId": "development",
"cache": { "cache": {
"lazyData": null, "lazyData": null,
"lazyDataResolved": false,
"parallelRoutes": Map { "parallelRoutes": Map {
"children" => Map { "children" => Map {
"parallel-tab-bar" => { "parallel-tab-bar" => {
...@@ -1637,6 +1641,7 @@ describe('navigateReducer', () => { ...@@ -1637,6 +1641,7 @@ describe('navigateReducer', () => {
"buildId": "development", "buildId": "development",
"cache": { "cache": {
"lazyData": null, "lazyData": null,
"lazyDataResolved": false,
"parallelRoutes": Map { "parallelRoutes": Map {
"children" => Map { "children" => Map {
"linking" => { "linking" => {
......
...@@ -166,6 +166,7 @@ describe('serverPatchReducer', () => { ...@@ -166,6 +166,7 @@ describe('serverPatchReducer', () => {
"buildId": "development", "buildId": "development",
"cache": { "cache": {
"lazyData": null, "lazyData": null,
"lazyDataResolved": false,
"parallelRoutes": Map { "parallelRoutes": Map {
"children" => Map { "children" => Map {
"linking" => { "linking" => {
...@@ -349,6 +350,7 @@ describe('serverPatchReducer', () => { ...@@ -349,6 +350,7 @@ describe('serverPatchReducer', () => {
"buildId": "development", "buildId": "development",
"cache": { "cache": {
"lazyData": null, "lazyData": null,
"lazyDataResolved": false,
"parallelRoutes": Map { "parallelRoutes": Map {
"children" => Map { "children" => Map {
"linking" => { "linking" => {
......
...@@ -19,6 +19,11 @@ export type ChildSegmentMap = Map<string, CacheNode> ...@@ -19,6 +19,11 @@ export type ChildSegmentMap = Map<string, CacheNode>
export type CacheNode = ReadyCacheNode | LazyCacheNode export type CacheNode = ReadyCacheNode | LazyCacheNode
export type LazyCacheNode = { export type LazyCacheNode = {
/**
* Whether the lazy cache node data promise has been resolved.
* This value is only true after we've called `use` on the promise (and applied the data to the tree).
*/
lazyDataResolved?: boolean
/** /**
* When rsc is null, this is a lazily-initialized cache node. * When rsc is null, this is a lazily-initialized cache node.
* *
...@@ -61,6 +66,11 @@ export type LazyCacheNode = { ...@@ -61,6 +66,11 @@ export type LazyCacheNode = {
} }
export type ReadyCacheNode = { export type ReadyCacheNode = {
/**
* Whether the lazy cache node data promise has been resolved.
* This value is only true after we've called `use` on the promise (and applied the data to the tree).
*/
lazyDataResolved?: boolean
/** /**
* When rsc is not null, it represents the RSC data for the * When rsc is not null, it represents the RSC data for the
* corresponding segment. * corresponding segment.
......
...@@ -140,8 +140,8 @@ function dispatchAction( ...@@ -140,8 +140,8 @@ function dispatchAction(
const newAction: ActionQueueNode = { const newAction: ActionQueueNode = {
payload, payload,
next: null, next: null,
resolve: resolvers!.resolve, resolve: resolvers.resolve,
reject: resolvers!.reject, reject: resolvers.reject,
} }
// Check if the queue is empty // Check if the queue is empty
......
'use server'
import { revalidatePath } from 'next/cache'
export async function action() {
revalidatePath('/', 'layout')
return true
}
'use client'
import { useFormState } from 'react-dom'
import { action } from './action'
export default function Page() {
const [submitted, formAction] = useFormState(action, false)
if (submitted) {
return <div>Form Submitted.</div>
}
return (
<div>
<h1>Form</h1>
<form action={formAction}>
<button id="submit-button">Push this button to submit the form</button>
</form>
</div>
)
}
import Link from 'next/link'
export default async function Home() {
await new Promise((resolve) => setTimeout(resolve, 1500))
return (
<div>
<h1>Home</h1>
<Link href="/popstate-revalidate/foo">To /foo</Link>
</div>
)
}
...@@ -817,5 +817,28 @@ createNextDescribe( ...@@ -817,5 +817,28 @@ createNextDescribe(
}) })
}) })
}) })
describe('browser back to a revalidated page', () => {
it('should load the page', async () => {
const browser = await next.browser('/popstate-revalidate')
expect(await browser.elementByCss('h1').text()).toBe('Home')
await browser.elementByCss("[href='/popstate-revalidate/foo']").click()
await browser.waitForElementByCss('#submit-button')
expect(await browser.elementByCss('h1').text()).toBe('Form')
await browser.elementById('submit-button').click()
await retry(async () => {
expect(await browser.elementByCss('body').text()).toContain(
'Form Submitted.'
)
})
await browser.back()
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe('Home')
})
})
})
} }
) )
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