Unverified Commit 854fdb03 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

instant(): Block out-of-band client fetches (#93099)

The Instant Navigation Testing API simulates what a user would see on an
arbitrarily slow connection — like an infinitely slow network — when the
app is at rest and the prefetch cache is completely warm. It works by
blocking any dynamic RSC data fetches until the end of the testing scope
(i.e. the callback passed to instant()).

It's designed to test the behavior of data fetched by Next.js, via a
Server Component. So currently, it does not affect the behavior
out-of-band client fetches — e.g. fetch('/api/...') in useEffect or an
external data fetching library. Those requests proceed without being
blocked by the `instant()` scope. But this is misleading for testing
purposes, because it implies that client-side data fetches are not
affected by slow network conditions.

To address this, this PR overrides the global `fetch` API and blocks
out-of-band client fetches until the lock is released. The change also
impacts the behavior of the Instant DevTools panel (since both tools use
the same underlying mechanism).

The change only affects environments where the Instant Navigation
Testing API is enabled. It has no impact on live production behavior. It
does not account for other sources of I/O, like images, scripts, fonts,
etc.

<!-- NEXT_JS_LLM_PR -->
parent a9cd6d7e
...@@ -32,6 +32,7 @@ ...@@ -32,6 +32,7 @@
const CONNECTIVITY_CHECK_TIMEOUT_MS = 200 const CONNECTIVITY_CHECK_TIMEOUT_MS = 200
import { pingPrefetchScheduler } from './segment-cache/scheduler' import { pingPrefetchScheduler } from './segment-cache/scheduler'
import { fetch } from './segment-cache/fetch'
import { RSC_HEADER } from './app-router-headers' import { RSC_HEADER } from './app-router-headers'
import { dispatchOfflineChange } from './use-offline' import { dispatchOfflineChange } from './use-offline'
......
...@@ -8,6 +8,7 @@ import { ...@@ -8,6 +8,7 @@ import {
} from 'react-server-dom-webpack/client' } from 'react-server-dom-webpack/client'
import { InvariantError } from '../../../shared/lib/invariant-error' import { InvariantError } from '../../../shared/lib/invariant-error'
import { fetch } from '../segment-cache/fetch'
import type { import type {
FlightRouterState, FlightRouterState,
InitialRSCPayload, InitialRSCPayload,
......
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
NEXT_REQUEST_ID_HEADER, NEXT_REQUEST_ID_HEADER,
} from '../../app-router-headers' } from '../../app-router-headers'
import { UnrecognizedActionError } from '../../unrecognized-action-error' import { UnrecognizedActionError } from '../../unrecognized-action-error'
import { fetch } from '../../segment-cache/fetch'
// TODO: Explicitly import from client.browser // TODO: Explicitly import from client.browser
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
......
...@@ -31,6 +31,7 @@ import { ...@@ -31,6 +31,7 @@ import {
type RSCResponse, type RSCResponse,
type RequestHeaders, type RequestHeaders,
} from '../router-reducer/fetch-server-response' } from '../router-reducer/fetch-server-response'
import { fetch } from './fetch'
import { import {
pingPrefetchTask, pingPrefetchTask,
isPrefetchTaskDirty, isPrefetchTaskDirty,
......
import { getPreLockFetch } from './navigation-testing-lock'
/**
* Internal `fetch` used by the Next.js client router.
*
* When the Instant Navigation Testing API is enabled, the navigation lock may
* install a blocking override on `window.fetch` for the duration of a lock
* scope. To let internal fetches bypass the lock, callers go through a wrapper
* that falls back to the pre-lock fetch captured at lock-acquire time.
*
* When the testing API is not enabled, this calls window.fetch directly.
*/
function fetchInternal(
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response> {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const preLockFetch = getPreLockFetch()
if (preLockFetch !== null) {
return preLockFetch(input, init)
}
}
return fetch(input, init)
}
export { fetchInternal as fetch }
...@@ -48,8 +48,17 @@ function writeCookieValue(value: InstantCookie): void { ...@@ -48,8 +48,17 @@ function writeCookieValue(value: InstantCookie): void {
// then write back with the new value. This updates the same cookie // then write back with the new value. This updates the same cookie
// entry that the external actor created, regardless of how it was // entry that the external actor created, regardless of how it was
// scoped. // scoped.
//
// Capture the current lockState and compare it in the callback so we
// only write if the lock we observed at call time is still held. This
// guards against two races: (a) the scope ended between get and set
// (lockState is now null), and (b) the scope ended and a new one was
// acquired in the same gap (lockState is a different object). In
// either case we must not write — doing so would leak stale state
// into the next scope or outlive the current one.
const lockAtCall = lockState
cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((existing: any) => { cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((existing: any) => {
if (existing) { if (existing && lockState === lockAtCall && lockAtCall !== null) {
const options: any = { const options: any = {
name: NEXT_INSTANT_TEST_COOKIE, name: NEXT_INSTANT_TEST_COOKIE,
value: JSON.stringify(value), value: JSON.stringify(value),
...@@ -66,10 +75,19 @@ function writeCookieValue(value: InstantCookie): void { ...@@ -66,10 +75,19 @@ function writeCookieValue(value: InstantCookie): void {
type NavigationLockState = { type NavigationLockState = {
promise: Promise<void> promise: Promise<void>
resolve: () => void resolve: () => void
// The pre-lock `window.fetch`, captured at `acquireLock` time and
// restored at `releaseLock`. Internal Next.js code reads this via
// `getPreLockFetch` to bypass the override we install on `window.fetch`
// during a lock scope.
fetch: typeof fetch
} }
let lockState: NavigationLockState | null = null let lockState: NavigationLockState | null = null
export function getPreLockFetch(): typeof fetch | null {
return lockState !== null ? lockState.fetch : null
}
function acquireLock(): void { function acquireLock(): void {
if (lockState !== null) { if (lockState !== null) {
return return
...@@ -78,14 +96,61 @@ function acquireLock(): void { ...@@ -78,14 +96,61 @@ function acquireLock(): void {
const promise = new Promise<void>((r) => { const promise = new Promise<void>((r) => {
resolve = r resolve = r
}) })
lockState = { promise, resolve: resolve! } lockState = { promise, resolve: resolve!, fetch: window.fetch }
// Install the fetch blocker. We only intercept `window.fetch` for the
// duration of the lock so that — outside of a testing scope — user-
// installed overrides of `window.fetch` are untouched.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
window.fetch = globalFetchOverride
}
} }
function releaseLock(): void { function releaseLock(): void {
if (lockState !== null) { if (lockState === null) {
lockState.resolve() return
lockState = null }
// Restore the pre-lock `window.fetch` before resolving the lock promise
// so any fetches queued on the promise see the restored fetch.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
window.fetch = lockState.fetch
} }
const { resolve } = lockState
lockState = null
resolve()
}
/**
* Global fetch override
*
* While the navigation lock is active, we install this as `window.fetch` so
* out-of-band client-side fetches (e.g. `fetch('/api/data')` inside a
* useEffect) are blocked until the lock is released. Next.js internals
* bypass the override by importing `fetch` from `./fetch`, which reads the
* captured pre-lock fetch via `getPreLockFetch`.
*
* NOTE: This override only affects environments where the Instant Navigation
* Testing API is enabled. It has no impact on live production behavior.
*/
export function globalFetchOverride(
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response> {
if (lockState === null) {
// Lock is not active. Fall through to the global fetch — we reach this
// only if a caller captured a reference to this function during a lock
// scope and invoked it after release.
return fetch(input, init)
}
// Block user-initiated fetches until the lock is released, then dispatch
// through the fetch captured at acquire time. Reading from `lockState`
// (rather than `window.fetch`) pins to the capture even if `window.fetch`
// is reassigned after release.
const currentLock = lockState
return currentLock.promise.then(() => {
const preLockFetch = currentLock.fetch
return preLockFetch(input, init)
})
} }
/** /**
......
import { NextResponse } from 'next/server'
export async function GET() {
return NextResponse.json({ message: 'api response' })
}
'use client'
import { useState, useEffect } from 'react'
export default function ClientFetchPage() {
const [data, setData] = useState<string | null>(null)
useEffect(() => {
fetch('/api/data')
.then((res) => res.json())
.then((json) => setData(json.message))
}, [])
return (
<div>
<h1 data-testid="client-fetch-title">Client Fetch Page</h1>
{data ? (
<div data-testid="fetched-data">{data}</div>
) : (
<div data-testid="fetched-data-loading">Loading data...</div>
)}
</div>
)
}
...@@ -48,6 +48,12 @@ export default function HomePage() { ...@@ -48,6 +48,12 @@ export default function HomePage() {
<a href="/search-params-page?foo=bar" id="plain-link-to-search-params"> <a href="/search-params-page?foo=bar" id="plain-link-to-search-params">
Go to search params page (MPA) Go to search params page (MPA)
</a> </a>
<Link href="/client-fetch-page" id="link-to-client-fetch">
Go to client fetch page
</Link>
<a href="/client-fetch-page" id="plain-link-to-client-fetch">
Go to client fetch page (MPA)
</a>
</div> </div>
) )
} }
...@@ -696,6 +696,56 @@ describe('instant-navigation-testing-api', () => { ...@@ -696,6 +696,56 @@ describe('instant-navigation-testing-api', () => {
expect(instantCookie).toBeUndefined() expect(instantCookie).toBeUndefined()
}) })
it('blocks out-of-band client fetch during instant scope (SPA)', async () => {
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#link-to-client-fetch')
// The page title appears (it's a client component, rendered immediately)
const title = page.locator('[data-testid="client-fetch-title"]')
await title.waitFor({ state: 'visible' })
// The fetch to /api/data is blocked, so the loading state persists
const loading = page.locator('[data-testid="fetched-data-loading"]')
await loading.waitFor({ state: 'visible' })
// The fetched data has NOT arrived
const fetchedData = page.locator('[data-testid="fetched-data"]')
expect(await fetchedData.count()).toBe(0)
})
// After exiting the instant scope, the fetch completes
const fetchedData = page.locator('[data-testid="fetched-data"]')
await fetchedData.waitFor({ state: 'visible' })
expect(await fetchedData.textContent()).toContain('api response')
})
it('blocks out-of-band client fetch during instant scope (MPA)', async () => {
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#plain-link-to-client-fetch')
// The page title appears
const title = page.locator('[data-testid="client-fetch-title"]')
await title.waitFor({ state: 'visible' })
// The fetch to /api/data is blocked, so the loading state persists
const loading = page.locator('[data-testid="fetched-data-loading"]')
await loading.waitFor({ state: 'visible' })
// The fetched data has NOT arrived
const fetchedData = page.locator('[data-testid="fetched-data"]')
expect(await fetchedData.count()).toBe(0)
})
// After exiting the instant scope, the fetch completes
const fetchedData = page.locator('[data-testid="fetched-data"]')
await fetchedData.waitFor({ state: 'visible' })
expect(await fetchedData.textContent()).toContain('api response')
})
it('clears cookie even when callback throws', async () => { it('clears cookie even when callback throws', async () => {
const page = await openPage(next, '/') const page = await openPage(next, '/')
......
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