Unverified Commit 66de92de authored by David Alexandru Ilie's avatar David Alexandru Ilie Committed by GitHub

Retry HTTP access fallbacks after refresh

parent 30e73d2d
...@@ -25,6 +25,8 @@ interface HTTPAccessFallbackBoundaryProps { ...@@ -25,6 +25,8 @@ interface HTTPAccessFallbackBoundaryProps {
notFound?: React.ReactNode notFound?: React.ReactNode
forbidden?: React.ReactNode forbidden?: React.ReactNode
unauthorized?: React.ReactNode unauthorized?: React.ReactNode
/** Changes when the boundary should retry rendering its children. */
resetKey?: unknown
// TODO: Make this required once `React.createElement` understands that positional args go into children // TODO: Make this required once `React.createElement` understands that positional args go into children
children?: React.ReactNode children?: React.ReactNode
missingSlots?: Set<string> missingSlots?: Set<string>
...@@ -39,6 +41,7 @@ interface HTTPAccessFallbackErrorBoundaryProps ...@@ -39,6 +41,7 @@ interface HTTPAccessFallbackErrorBoundaryProps
interface HTTPAccessBoundaryState { interface HTTPAccessBoundaryState {
triggeredStatus: number | undefined triggeredStatus: number | undefined
previousPathname: string | null previousPathname: string | null
previousResetKey: unknown
} }
class HTTPAccessFallbackErrorBoundary extends React.Component< class HTTPAccessFallbackErrorBoundary extends React.Component<
...@@ -50,6 +53,7 @@ class HTTPAccessFallbackErrorBoundary extends React.Component< ...@@ -50,6 +53,7 @@ class HTTPAccessFallbackErrorBoundary extends React.Component<
this.state = { this.state = {
triggeredStatus: undefined, triggeredStatus: undefined,
previousPathname: props.pathname, previousPathname: props.pathname,
previousResetKey: props.resetKey,
} }
} }
...@@ -94,20 +98,28 @@ class HTTPAccessFallbackErrorBoundary extends React.Component< ...@@ -94,20 +98,28 @@ class HTTPAccessFallbackErrorBoundary extends React.Component<
state: HTTPAccessBoundaryState state: HTTPAccessBoundaryState
): HTTPAccessBoundaryState | null { ): HTTPAccessBoundaryState | null {
/** /**
* Handles reset of the error boundary when a navigation happens. * Handles reset of the error boundary when a navigation happens or when
* Ensures the error boundary does not stay enabled when navigating to a new page. * data for the current segment is replaced. The latter is needed for
* Approach of setState in render is safe as it checks the previous pathname and then overrides * same-path refreshes, which preserve the pathname and React state.
* it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders * Approach of setState in render is safe as it checks the previous values
* and then overrides them as outlined in
* https://react.dev/reference/react/useState#storing-information-from-previous-renders
*/ */
if (props.pathname !== state.previousPathname && state.triggeredStatus) { if (
(props.pathname !== state.previousPathname ||
props.resetKey !== state.previousResetKey) &&
state.triggeredStatus
) {
return { return {
triggeredStatus: undefined, triggeredStatus: undefined,
previousPathname: props.pathname, previousPathname: props.pathname,
previousResetKey: props.resetKey,
} }
} }
return { return {
triggeredStatus: state.triggeredStatus, triggeredStatus: state.triggeredStatus,
previousPathname: props.pathname, previousPathname: props.pathname,
previousResetKey: props.resetKey,
} }
} }
...@@ -155,6 +167,7 @@ export function HTTPAccessFallbackBoundary({ ...@@ -155,6 +167,7 @@ export function HTTPAccessFallbackBoundary({
notFound, notFound,
forbidden, forbidden,
unauthorized, unauthorized,
resetKey,
children, children,
}: HTTPAccessFallbackBoundaryProps) { }: HTTPAccessFallbackBoundaryProps) {
// When we're rendering the missing params shell, this will return null. This // When we're rendering the missing params shell, this will return null. This
...@@ -169,6 +182,7 @@ export function HTTPAccessFallbackBoundary({ ...@@ -169,6 +182,7 @@ export function HTTPAccessFallbackBoundary({
return ( return (
<HTTPAccessFallbackErrorBoundary <HTTPAccessFallbackErrorBoundary
pathname={pathname} pathname={pathname}
resetKey={resetKey}
notFound={notFound} notFound={notFound}
forbidden={forbidden} forbidden={forbidden}
unauthorized={unauthorized} unauthorized={unauthorized}
......
...@@ -699,6 +699,9 @@ export default function OuterLayoutRouter({ ...@@ -699,6 +699,9 @@ export default function OuterLayoutRouter({
notFound={notFound} notFound={notFound}
forbidden={forbidden} forbidden={forbidden}
unauthorized={unauthorized} unauthorized={unauthorized}
// A refresh replaces the segment's RSC attempt while preserving
// its React state identity.
resetKey={cacheNode.rsc}
> >
<RedirectBoundary> <RedirectBoundary>
<InnerLayoutRouter <InnerLayoutRouter
......
...@@ -381,7 +381,7 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -381,7 +381,7 @@ describe(`Terminal Logging (${bundlerName})`, () => {
<InnerScrollHandler scrollRef={{scrollRef:null, ...}} cacheNode={{rsc:{...}, ...}}> <InnerScrollHandler scrollRef={{scrollRef:null, ...}} cacheNode={{rsc:{...}, ...}}>
<ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}> <ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}>
<LoadingBoundary name="hydration-..." loading={null}> <LoadingBoundary name="hydration-..." loading={null}>
<HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}> <HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined} ...>
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/hydration..." tree={[...]} params={{}} cacheNode={{rsc:{...}, ...}} ...> <InnerLayoutRouter url="/hydration..." tree={[...]} params={{}} cacheNode={{rsc:{...}, ...}} ...>
......
import { LinkAccordion } from '../components/link-accordion'
export default function NotFound() {
return (
<main id="blog-not-found">
<p>Blog category not found</p>
<LinkAccordion href="/blog" prefetch={false}>
Visit all posts
</LinkAccordion>
</main>
)
}
import { notFound } from 'next/navigation'
import { Suspense } from 'react'
async function BlogContent({
searchParams,
}: {
searchParams: Promise<{ category?: string }>
}) {
const { category } = await searchParams
if (category === 'invalid') {
notFound()
}
return (
<main id="blog-content">
<p>All posts</p>
</main>
)
}
export default function Page({
searchParams,
}: {
searchParams: Promise<{ category?: string }>
}) {
return (
<Suspense fallback={<p id="loading">Loading...</p>}>
<BlogContent searchParams={searchParams} />
</Suspense>
)
}
'use client'
import { useRouter } from 'next/navigation'
import { useTransition } from 'react'
export function AccessToggle({ access }: { access: 'grant' | 'revoke' }) {
const router = useRouter()
const [isPending, startTransition] = useTransition()
const isGrant = access === 'grant'
return (
<button
id={isGrant ? 'grant-access' : 'revoke-access'}
disabled={isPending}
onClick={() => {
document.cookie = isGrant
? 'refresh-access=granted; path=/; SameSite=Lax'
: 'refresh-access=; path=/; max-age=0; SameSite=Lax'
startTransition(() => router.refresh())
}}
>
{isGrant ? 'Grant access' : 'Revoke access'}
</button>
)
}
'use client'
import { useRouter } from 'next/navigation'
import { useEffect, useRef, useState, useTransition } from 'react'
export function FallbackState() {
const router = useRouter()
const [isPending, startTransition] = useTransition()
const [value, setValue] = useState('')
const [mountId, setMountId] = useState('')
const didSetMountId = useRef(false)
useEffect(() => {
if (!didSetMountId.current) {
didSetMountId.current = true
setMountId(crypto.randomUUID())
}
}, [])
return (
<>
<label>
Fallback state
<input
id="fallback-state"
value={value}
onChange={(event) => setValue(event.target.value)}
/>
</label>
<output id="fallback-mount-id">{mountId}</output>
<button
id="refresh-not-found"
disabled={isPending}
onClick={() => startTransition(() => router.refresh())}
>
Refresh while not found
</button>
</>
)
}
'use client'
import { useState } from 'react'
export function LayoutState() {
const [value, setValue] = useState('')
return (
<label>
Layout state
<input
id="layout-state"
value={value}
onChange={(event) => setValue(event.target.value)}
/>
</label>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
import type { ReactNode } from 'react'
import { LayoutState } from './components/layout-state'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>
<LayoutState />
{children}
</body>
</html>
)
}
import { AccessToggle } from './components/access-toggle'
import { FallbackState } from './components/fallback-state'
export default function NotFound() {
return (
<main id="access-not-found">
<p>Access not found</p>
<FallbackState />
<AccessToggle access="grant" />
</main>
)
}
import { LinkAccordion } from './components/link-accordion'
export default function Page() {
return (
<main id="home">
<p>Home</p>
<LinkAccordion href="/protected" prefetch={false}>
Visit protected page
</LinkAccordion>
<LinkAccordion href="/blog?category=invalid" prefetch={false}>
Visit invalid blog category
</LinkAccordion>
</main>
)
}
import { cookies } from 'next/headers'
import { notFound } from 'next/navigation'
import { Suspense } from 'react'
import { AccessToggle } from '../components/access-toggle'
async function ProtectedContent() {
const cookieStore = await cookies()
if (cookieStore.get('refresh-access')?.value !== 'granted') {
notFound()
}
return (
<main id="protected-content">
<p>Protected content</p>
<AccessToggle access="revoke" />
</main>
)
}
export default function Page() {
return (
<Suspense fallback={<p id="loading">Loading...</p>}>
<ProtectedContent />
</Suspense>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
describe('HTTP access fallback refresh', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('resets a not-found boundary when the same route is refreshed', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
await browser.waitForElementByCss('#home')
await browser.elementById('layout-state').type('preserved')
await browser.eval(`window.__httpAccessFallbackDocument = 'preserved'`)
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/protected"]')
.click()
await browser.elementByCss('a[href="/protected"]').click()
})
await retry(async () => {
expect(await browser.hasElementByCss('#access-not-found')).toBe(true)
})
const protectedUrl = await browser.url()
await browser.elementById('fallback-state').type('preserved')
async function readFallbackMountId() {
let mountId = ''
await retry(async () => {
mountId = await browser.elementById('fallback-mount-id').text()
expect(mountId).not.toBe('')
})
return mountId
}
const initialFallbackMountId = await readFallbackMountId()
async function expectDocumentStateToBePreserved() {
expect(await browser.url()).toBe(protectedUrl)
expect(await browser.elementById('layout-state').getValue()).toBe(
'preserved'
)
expect(await browser.eval(`window.__httpAccessFallbackDocument`)).toBe(
'preserved'
)
}
await expectDocumentStateToBePreserved()
await act(
async () => {
await browser.elementById('refresh-not-found').click()
},
{ includes: 'Access not found' }
)
await retry(async () => {
expect(await browser.hasElementByCss('#access-not-found')).toBe(true)
})
const retriedFallbackMountId = await readFallbackMountId()
// Retrying a boundary that still throws replaces its fallback subtree once.
// It must then settle without replacing the document/layout or continuing
// to remount the fallback.
expect(retriedFallbackMountId).not.toBe(initialFallbackMountId)
expect(await browser.elementById('fallback-state').getValue()).toBe('')
await retry(async () => {
expect(
await browser.eval(
`document.getElementById('refresh-not-found').disabled`
)
).toBe(false)
})
for (let i = 0; i < 3; i++) {
await browser.eval(`new Promise(requestAnimationFrame)`)
expect(await browser.elementById('fallback-mount-id').text()).toBe(
retriedFallbackMountId
)
}
await expectDocumentStateToBePreserved()
await act(
async () => {
await browser.elementById('grant-access').click()
},
{ includes: 'Protected content' }
)
await retry(async () => {
expect(await browser.hasElementByCss('#protected-content')).toBe(true)
})
await expectDocumentStateToBePreserved()
await act(async () => {
await browser.elementById('revoke-access').click()
})
await retry(async () => {
expect(await browser.hasElementByCss('#access-not-found')).toBe(true)
})
await expectDocumentStateToBePreserved()
await act(
async () => {
await browser.elementById('grant-access').click()
},
{ includes: 'Protected content' }
)
await retry(async () => {
expect(await browser.hasElementByCss('#protected-content')).toBe(true)
})
await expectDocumentStateToBePreserved()
})
it('resets a not-found boundary after a search parameter change', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
await browser.waitForElementByCss('#home')
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/blog?category=invalid"]')
.click()
await browser.elementByCss('a[href="/blog?category=invalid"]').click()
})
await retry(async () => {
expect(await browser.hasElementByCss('#blog-not-found')).toBe(true)
})
await act(
async () => {
await browser.elementByCss('input[data-link-accordion="/blog"]').click()
await browser.elementByCss('a[href="/blog"]').click()
},
{ includes: 'All posts' }
)
await retry(async () => {
expect(await browser.hasElementByCss('#blog-content')).toBe(true)
})
expect(new URL(await browser.url()).search).toBe('')
})
})
/** @type {import('next').NextConfig} */
const nextConfig = {}
module.exports = nextConfig
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