Unverified Commit 90450112 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[experiment] Add useOffline flag with offline retry behavior (#92011)

**Current:**

1. https://github.com/vercel/next.js/pull/92011

**Up next:**

2. https://github.com/vercel/next.js/pull/92012

---

When a navigation, server action, or prefetch fails due to a network
error, instead of falling back to MPA navigation or surfacing an error,
the request blocks until connectivity is restored and then retries
automatically.

Offline detection works by treating any `fetch()` rejection as a network
error (server errors resolve with a status code, they don't reject).
Once offline, a polling loop does HEAD requests with exponential backoff
to detect when connectivity returns. Browser offline/online events also
feed into this loop. Successful fetches from other code paths can
short-circuit the loop if they happen to land first.

Follow-up work will add a `useOffline` hook so apps can show an offline
indicator to the user, and allow navigations to read from stale cache
entries while offline.

Gated behind `experimental.useOffline`.
parent d8b5ea2d
......@@ -245,6 +245,7 @@ export function getDefineEnv({
'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean(
config.experimental.dynamicOnHover
),
'process.env.__NEXT_USE_OFFLINE': Boolean(config.experimental.useOffline),
'process.env.__NEXT_PREFETCH_INLINING': Boolean(
config.experimental.prefetchInlining
),
......
......@@ -362,6 +362,12 @@ export async function hydrate(
}
const initialRSCPayload = await initialServerResponse
// Initialize the offline module to register browser event listeners
// (offline/online) before any components hydrate.
if (process.env.__NEXT_USE_OFFLINE) {
require('./components/offline') as typeof import('./components/offline')
}
// setNavigationBuildId should be called only once, during JS initialization
// and before any components have hydrated.
if (initialRSCPayload.b) {
......
/**
* Centralized offline detection, state management, and retry logic.
*
* This module tracks whether the app is offline and provides primitives for
* retrying failed network requests. It is designed to be extended in the
* future — e.g., instrumenting module chunk loading, Flight chunk resolution,
* or eventually being promoted to a React-level feature.
*
* All stateful behavior (event listeners, polling, state tracking) only runs
* in the browser. On the server and during hydration, getOffline() always
* returns false.
*
* ## Known limitation: queued fetches
*
* When the user navigates multiple times while offline, each navigation queues
* a separate fetch that blocks on waitForConnection(). When connectivity is
* restored, all of them resume and retry simultaneously.
*
* Future mitigations:
* - Stale cache access (PR 3): offline navigations will reuse back-forward
* cache entries, so most navigations won't issue new fetches at all. This is
* the primary shield against duplicate requests.
* - Fetch cancellation: on router.refresh(), we could abort pending blocked
* fetches since refresh invalidates all dynamic caches.
*/
// Backoff delays for the polling loop: 500ms → 1s → 2s → 3s (cap)
// Timeout for the HEAD connectivity check. If the request doesn't resolve
// within this window, we assume we're still offline. 200ms is more than enough
// — network errors reject almost instantly.
const CONNECTIVITY_CHECK_TIMEOUT_MS = 200
import { pingPrefetchScheduler } from './segment-cache/scheduler'
import { RSC_HEADER } from './app-router-headers'
export type OfflineState = {
promise: Promise<void>
resolve: () => void
timeoutHandle: ReturnType<typeof setTimeout> | null
backoffStep: number
}
let offlineState: OfflineState | null = null
/**
* Returns true if the error from a fetch() rejection indicates a network
* failure (as opposed to an intentional abort or timeout). If it is a
* network error, also starts the connectivity polling loop.
*
* - AbortError: the request was intentionally canceled via AbortSignal
* - TimeoutError: AbortSignal.timeout() expired — could be a slow server,
* not necessarily offline
*/
export function checkOfflineError(err: unknown): boolean {
if (err instanceof DOMException) {
if (err.name === 'AbortError' || err.name === 'TimeoutError') {
return false
}
}
notifyOffline()
return true
}
/**
* Returns whether the app is currently considered offline (i.e., a
* connectivity polling loop is active). Always returns false on the
* server and during hydration.
*/
export function getOffline(): OfflineState | null {
return offlineState
}
/**
* Enters the offline state if not already in it, and starts the
* connectivity polling loop.
*/
function notifyOffline(): OfflineState {
if (offlineState !== null) {
return offlineState
}
let resolve: () => void
const promise = new Promise<void>((r) => {
resolve = r
})
offlineState = {
promise,
resolve: resolve!,
timeoutHandle: null,
backoffStep: 0,
}
checkConnectivity(offlineState)
return offlineState
}
/**
* Call this when any network request succeeds while we're in the offline state.
* If a polling loop is active, this short-circuits it — no need to wait for
* the next HEAD check if we already know we're back online.
*/
export function notifyOnline(): void {
if (offlineState === null) {
return
}
if (offlineState.timeoutHandle !== null) {
clearTimeout(offlineState.timeoutHandle)
}
const resolve = offlineState.resolve
offlineState = null
resolve()
pingPrefetchScheduler()
}
/**
* Does a HEAD request to confirm connectivity, then either resolves the
* offline state or schedules the next check with backoff.
*/
async function checkConnectivity(state: OfflineState): Promise<void> {
// Cancel any previously scheduled check so we don't end up with
// parallel polling loops.
if (state.timeoutHandle !== null) {
clearTimeout(state.timeoutHandle)
state.timeoutHandle = null
}
const controller = new AbortController()
const timeoutId = setTimeout(
() => controller.abort(),
CONNECTIVITY_CHECK_TIMEOUT_MS
)
try {
// HEAD request to the current page with the RSC header, so we're
// testing connectivity to the same endpoint that navigations use.
await fetch(location.href, {
method: 'HEAD',
headers: { [RSC_HEADER]: '1' },
signal: controller.signal,
})
clearTimeout(timeoutId)
// If the fetch didn't throw, we're back online.
notifyOnline()
} catch (err) {
// If the error is from our own timeout abort, that actually means
// the request went out and is waiting for a response — i.e., we're
// back online. A truly offline request fails almost instantly (well
// within the 200ms timeout).
if (err instanceof DOMException && err.name === 'AbortError') {
clearTimeout(timeoutId)
notifyOnline()
return
}
// Network error — still offline. Schedule the next check with backoff.
const delay =
state.backoffStep === 0
? 500
: state.backoffStep === 1
? 1000
: state.backoffStep === 2
? 2000
: 3000
state.backoffStep++
state.timeoutHandle = setTimeout(() => checkConnectivity(state), delay)
}
}
/**
* Returns a promise that resolves when connectivity is restored.
*/
export function waitForConnection(state: OfflineState) {
return state.promise
}
function pingOfflineState() {
if (offlineState !== null) {
checkConnectivity(offlineState)
}
}
// Set up browser event listeners for proactive offline detection.
if (typeof window !== 'undefined') {
window.addEventListener('offline', notifyOffline)
window.addEventListener('online', pingOfflineState)
}
......@@ -190,6 +190,14 @@ export async function fetchServerResponse(
shouldImmediatelyDecode
)
// If the fetch succeeds while we're in the offline state, notify the
// offline module so it can short-circuit the polling loop.
if (process.env.__NEXT_USE_OFFLINE) {
const { notifyOnline } =
require('../offline') as typeof import('../offline')
notifyOnline()
}
const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))
const canonicalUrl = res.redirected ? responseUrl : originalUrl
......@@ -293,6 +301,28 @@ export async function fetchServerResponse(
debugInfo: flightResponsePromise._debugInfo ?? null,
}
} catch (err) {
// If the fetch rejected due to a network error, wait for connectivity
// to be restored and then retry. checkOfflineError returns true for
// network errors (and starts the polling loop); returns false for
// intentional aborts/timeouts, which fall through to the MPA fallback.
//
// Note: when the user navigates multiple times while offline, each
// navigation queues a separate retry here. Once connectivity returns,
// all pending retries resume simultaneously. This is mitigated in PR 3
// by reusing back-forward cache entries during offline navigation, which
// avoids issuing new fetches in the first place.
if (process.env.__NEXT_USE_OFFLINE && !isPageUnloading) {
const { checkOfflineError, getOffline, waitForConnection } =
require('../offline') as typeof import('../offline')
if (checkOfflineError(err)) {
const offline = getOffline()
if (offline !== null) {
await waitForConnection(offline)
}
return fetchServerResponse(url, options)
}
}
if (!isPageUnloading) {
console.error(
`Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,
......
......@@ -103,8 +103,9 @@ type FetchServerActionResult = {
async function fetchServerAction(
state: ReadonlyReducerState,
nextUrl: ReadonlyReducerState['nextUrl'],
{ actionId, actionArgs }: ServerActionAction
action: ServerActionAction
): Promise<FetchServerActionResult> {
const { actionId, actionArgs } = action
const temporaryReferences = createTemporaryReferenceSet()
const info = extractInfoFromServerReferenceId(actionId)
const usedArgs = omitUnusedArgs(actionArgs, info)
......@@ -140,7 +141,33 @@ async function fetchServerAction(
.toString(16)
}
const res = await fetch(state.canonicalUrl, { method: 'POST', headers, body })
let res: Response
try {
res = await fetch(state.canonicalUrl, { method: 'POST', headers, body })
// If the fetch succeeds while we're in the offline state, notify the
// offline module so it can short-circuit the polling loop.
if (process.env.__NEXT_USE_OFFLINE) {
const { notifyOnline } =
require('../../offline') as typeof import('../../offline')
notifyOnline()
}
} catch (err) {
if (process.env.__NEXT_USE_OFFLINE) {
const { checkOfflineError, getOffline, waitForConnection } =
require('../../offline') as typeof import('../../offline')
if (checkOfflineError(err)) {
// It's safe to replay the action because the fetch rejection
// means the request never reached the server — there are no
// side effects to duplicate.
const offline = getOffline()
if (offline !== null) {
await waitForConnection(offline)
}
return fetchServerAction(state, nextUrl, action)
}
}
throw err
}
// Handle server actions that the server didn't recognize.
const unrecognizedActionHeader = res.headers.get(NEXT_ACTION_NOT_FOUND_HEADER)
......
......@@ -1862,7 +1862,21 @@ export async function fetchRouteOnCacheMiss(
return { value: null, closed: closed.promise }
} catch (error) {
// Either the connection itself failed, or something bad happened while
// decoding the response.
// decoding the response. If we're offline, reject with staleAt=-1 so the
// entry immediately expires and gets retried once the scheduler is
// re-pinged after connectivity is restored.
if (process.env.__NEXT_USE_OFFLINE) {
const { checkOfflineError } =
require('../offline') as typeof import('../offline')
if (checkOfflineError(error)) {
// Unlike navigations and server actions, prefetches don't await
// waitForConnection — they just reject the cache entry with an
// immediate expiration so it gets retried once the scheduler is
// re-pinged after connectivity is restored.
rejectRouteCacheEntry(entry, -1)
return null
}
}
rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)
return null
}
......@@ -2065,6 +2079,18 @@ export async function fetchSegmentsOnCacheMiss(
} catch (error) {
// Either the connection itself failed, or something bad happened while
// decoding the response.
if (process.env.__NEXT_USE_OFFLINE) {
const { checkOfflineError } =
require('../offline') as typeof import('../offline')
if (checkOfflineError(error)) {
// Unlike navigations and server actions, prefetches don't await
// waitForConnection — they just reject the cache entry with an
// immediate expiration so it gets retried once the scheduler is
// re-pinged after connectivity is restored.
rejectRemainingSegmentsInBundle(segments, -1)
return null
}
}
rejectRemainingSegmentsInBundle(segments, Date.now() + 10 * 1000)
return null
}
......@@ -2263,6 +2289,18 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
// the scheduler can track the number of concurrent network connections.
return { value: null, closed: closed.promise }
} catch (error) {
if (process.env.__NEXT_USE_OFFLINE) {
const { checkOfflineError } =
require('../offline') as typeof import('../offline')
if (checkOfflineError(error)) {
// Unlike navigations and server actions, prefetches don't await
// waitForConnection — they just reject the cache entry with an
// immediate expiration so it gets retried once the scheduler is
// re-pinged after connectivity is restored.
rejectSegmentEntriesIfStillPending(spawnedEntries, -1)
return null
}
}
rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)
return null
}
......
......@@ -418,6 +418,15 @@ export function pingPrefetchScheduler() {
* prefetch requests are delayed to allow CDN cache propagation.
*/
function hasNetworkBandwidth(task: PrefetchTask): boolean {
// When offline, don't issue any prefetch requests. The scheduler will be
// re-pinged when connectivity is restored.
if (process.env.__NEXT_USE_OFFLINE) {
const { getOffline } = require('../offline') as typeof import('../offline')
if (getOffline()) {
return false
}
}
// Check if we're within the revalidation cooldown window
if (revalidationCooldownTimeoutHandle !== null) {
// We're within the cooldown window. Return false to prevent prefetching.
......
......@@ -221,6 +221,7 @@ export const experimentalSchema = {
cachedNavigations: z.boolean().optional(),
partialFallbacks: z.boolean().optional(),
dynamicOnHover: z.boolean().optional(),
useOffline: z.boolean().optional(),
optimisticRouting: z.boolean().optional(),
varyParams: z.boolean().optional(),
prefetchInlining: z
......
......@@ -415,6 +415,7 @@ export interface ExperimentalConfig {
*/
partialFallbacks?: boolean
dynamicOnHover?: boolean
useOffline?: boolean
optimisticRouting?: boolean
varyParams?: boolean
prefetchInlining?:
......@@ -1734,6 +1735,7 @@ export const defaultConfig = Object.freeze({
cachedNavigations: false,
partialFallbacks: false,
dynamicOnHover: false,
useOffline: false,
varyParams: false,
prefetchInlining: false,
preloadEntriesOnStart: true,
......@@ -1879,6 +1881,7 @@ export interface NextConfigRuntime {
| 'serverActions'
| 'staleTimes'
| 'dynamicOnHover'
| 'useOffline'
| 'optimisticRouting'
| 'inlineCss'
| 'prefetchInlining'
......@@ -1945,6 +1948,7 @@ export function getNextConfigRuntime(
serverActions: ex.serverActions,
staleTimes: ex.staleTimes,
dynamicOnHover: ex.dynamicOnHover,
useOffline: ex.useOffline,
optimisticRouting: ex.optimisticRouting,
inlineCss: ex.inlineCss,
prefetchInlining: ex.prefetchInlining,
......
import { connection } from 'next/server'
export default async function DestinationPage() {
await connection()
return <div id="destination-content">Destination page content</div>
}
import { Suspense } from 'react'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>
<Suspense fallback={<div id="loading">Loading...</div>}>
{children}
</Suspense>
</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default function Home() {
return (
<div id="home">
<h1>Home</h1>
<LinkAccordion href="/destination">Destination page</LinkAccordion>
</div>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: boolean
}) {
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)`
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
useOffline: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
import { retry } from 'next-test-utils'
describe('useOffline - retry behavior', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('skipped in dev mode', () => {})
return
}
// Uses Playwright's built-in network emulation, which fires the browser's
// native offline/online events and blocks all requests at the network layer.
async function goOffline(page: Playwright.Page) {
await page.context().setOffline(true)
}
async function goOnline(page: Playwright.Page) {
await page.context().setOffline(false)
}
it('retries navigation after connectivity is restored', async () => {
let act: ReturnType<typeof createRouterAct>
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
act = createRouterAct(p)
},
})
// Verify we're on the home page
expect(await browser.elementById('home').text()).toContain('Home')
// Prefetch the target link
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/destination"]'
)
await toggle.click()
})
// Go offline, then click the link.
await goOffline(page!)
const link = await browser.elementByCss('a[href="/destination"]')
await link.click()
// The navigation is stuck in a pending transition — React keeps showing
// the current page. The target content should not be visible.
expect(await browser.hasElementByCssSelector('#destination-content')).toBe(
false
)
expect(await browser.elementById('home').text()).toContain('Home')
// Restore connectivity. The retry loop should detect this and
// complete the navigation.
await goOnline(page!)
await retry(async () => {
expect(await browser.elementById('destination-content').text()).toBe(
'Destination page content'
)
})
})
})
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