Skip to content

Detect lazy route discovery manifest version mismatches and trigger reloads #13061

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/real-adults-protect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"react-router": minor
---

Add `fetcherKey` as a parameter to `patchRoutesOnNavigation`

- In framework mode, Lazy Route Discovery will now detect manifest version mismatches after a new deploy
- On navigations to undiscovered routes, this mismatch will trigger a document reload of the destination path
- On `fetcher` calls to undiscovered routes, this mismatch will trigger a document reload of the current path
45 changes: 44 additions & 1 deletion packages/react-router/lib/dom/ssr/fog-of-war.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,13 @@ export function getPatchRoutesOnNavigationFunction(
return undefined;
}

return async ({ path, patch, signal }) => {
return async ({ path, patch, signal, fetcherKey }) => {
if (discoveredPaths.has(path)) {
return;
}
await fetchAndApplyManifestPatches(
[path],
fetcherKey ? window.location.href : path,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reload the current path on fetcher calls, or the next path on navigations

manifest,
routeModules,
ssr,
Expand Down Expand Up @@ -149,6 +150,7 @@ export function useFogOFWarDiscovery(
try {
await fetchAndApplyManifestPatches(
lazyPaths,
null,
manifest,
routeModules,
ssr,
Expand Down Expand Up @@ -181,8 +183,11 @@ export function useFogOFWarDiscovery(
}, [ssr, isSpaMode, manifest, routeModules, router]);
}

const MANIFEST_VERSION_STORAGE_KEY = "react-router-manifest-version";

export async function fetchAndApplyManifestPatches(
paths: string[],
errorReloadPath: string | null,
manifest: AssetsManifest,
routeModules: RouteModules,
ssr: boolean,
Expand Down Expand Up @@ -213,10 +218,48 @@ export async function fetchAndApplyManifestPatches(

if (!res.ok) {
throw new Error(`${res.status} ${res.statusText}`);
} else if (
res.status === 204 &&
res.headers.has("X-Remix-Reload-Document")
) {
if (!errorReloadPath) {
// No-op during eager route discovery so we will trigger a hard reload
// of the destination during the next navigation instead of reloading
// while the user is sitting on the current page. Slightly more
// disruptive on fetcher calls because we reload the current page, but
// it's better than the `React.useContext` error that occurs without
// this detection.
console.warn(
"Detected a manifest version mismatch during eager route discovery. " +
"The next navigation/fetch to an undiscovered route will result in " +
"a new document navigation to sync up with the latest manifest."
);
return;
}

// This will hard reload the destination path on navigations, or the
// current path on fetcher calls
if (
sessionStorage.getItem(MANIFEST_VERSION_STORAGE_KEY) ===
manifest.version
) {
// We've already tried fixing for this version, don' try again to
// avoid loops - just let this navigation/fetch 404
console.error(
"Unable to discover routes due to manifest version mismatch."
);
return;
}

sessionStorage.setItem(MANIFEST_VERSION_STORAGE_KEY, manifest.version);
window.location.href = errorReloadPath;
throw new Error("Detected manifest version mismatch, reloading...");
} else if (res.status >= 400) {
throw new Error(await res.text());
}

// Reset loop-detection on a successful response
sessionStorage.removeItem(MANIFEST_VERSION_STORAGE_KEY);
serverPatches = (await res.json()) as AssetsManifest["routes"];
} catch (e) {
if (signal?.aborted) return;
Expand Down
10 changes: 7 additions & 3 deletions packages/react-router/lib/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2225,7 +2225,8 @@ export function createRouter(init: RouterInit): Router {
let discoverResult = await discoverRoutes(
requestMatches,
path,
fetchRequest.signal
fetchRequest.signal,
key
);

if (discoverResult.type === "aborted") {
Expand Down Expand Up @@ -2509,7 +2510,8 @@ export function createRouter(init: RouterInit): Router {
let discoverResult = await discoverRoutes(
matches,
path,
fetchRequest.signal
fetchRequest.signal,
key
);

if (discoverResult.type === "aborted") {
Expand Down Expand Up @@ -3168,7 +3170,8 @@ export function createRouter(init: RouterInit): Router {
async function discoverRoutes(
matches: AgnosticDataRouteMatch[],
pathname: string,
signal: AbortSignal
signal: AbortSignal,
fetcherKey?: string
): Promise<DiscoverRoutesResult> {
if (!patchRoutesOnNavigationImpl) {
return { type: "success", matches };
Expand All @@ -3184,6 +3187,7 @@ export function createRouter(init: RouterInit): Router {
signal,
path: pathname,
matches: partialMatches,
fetcherKey,
patch: (routeId, children) => {
if (signal.aborted) return;
patchRoutesImpl(
Expand Down
1 change: 1 addition & 0 deletions packages/react-router/lib/router/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ export type AgnosticPatchRoutesOnNavigationFunctionArgs<
signal: AbortSignal;
path: string;
matches: M[];
fetcherKey: string | undefined;
patch: (routeId: string | null, children: O[]) => void;
};

Expand Down
9 changes: 9 additions & 0 deletions packages/react-router/lib/server-runtime/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,15 @@ async function handleManifestRequest(
routes: ServerRoute[],
url: URL
) {
if (build.assets.version !== url.searchParams.get("version")) {
return new Response(null, {
status: 204,
headers: {
"X-Remix-Reload-Document": "true",
},
});
}

let patches: Record<string, EntryRoute> = {};

if (url.searchParams.has("p")) {
Expand Down