Skip to content

Add config option to disable lazy route discovery #13451

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 9 commits into from
Apr 28, 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
13 changes: 13 additions & 0 deletions .changeset/angry-students-pay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
"@react-router/dev": minor
"react-router": minor
---

Added a new `react-router.config.ts` `routeDiscovery` option to configure Lazy Route Discovery behavior.

- By default, Lazy Route Discovery is enabled and makes manifest requests to the `/__manifest` path:
- `routeDiscovery: { mode: "lazy", manifestPath: "/__manifest" }`
- You can modify the manifest path used:
- `routeDiscovery: { mode: "lazy", manifestPath: "/custom-manifest" }`
- Or you can disable this feature entirely and include all routes in the manifest on initial document load:
- `routeDiscovery: { mode: "initial" }`
220 changes: 220 additions & 0 deletions integration/fog-of-war-test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { test, expect } from "@playwright/test";
import { PassThrough } from "node:stream";

import {
createAppFixture,
createFixture,
js,
} from "./helpers/create-fixture.js";
import { PlaywrightFixture } from "./helpers/playwright-fixture.js";
import { reactRouterConfig } from "./helpers/vite.js";

function getFiles() {
return {
Expand Down Expand Up @@ -118,6 +120,10 @@ test.describe("Fog of War", () => {
let res = await fixture.requestDocument("/");
let html = await res.text();

expect(html).toContain("window.__reactRouterManifest = {");
expect(html).not.toContain(
'<link rel="modulepreload" href="/assets/manifest-'
);
expect(html).toContain('"root": {');
expect(html).toContain('"routes/_index": {');
expect(html).not.toContain('"routes/a"');
Expand Down Expand Up @@ -1402,4 +1408,218 @@ test.describe("Fog of War", () => {
await app.clickLink("/a");
await page.waitForSelector("#a-index");
});

test("allows configuration of the manifest path", async ({ page }) => {
let fixture = await createFixture({
files: {
...getFiles(),
"react-router.config.ts": reactRouterConfig({
routeDiscovery: { mode: "lazy", manifestPath: "/custom-manifest" },
}),
},
});
let appFixture = await createAppFixture(fixture);
let app = new PlaywrightFixture(appFixture, page);

let wrongManifestRequests: string[] = [];
let manifestRequests: string[] = [];
page.on("request", (req) => {
if (req.url().includes("/__manifest")) {
wrongManifestRequests.push(req.url());
}
if (req.url().includes("/custom-manifest")) {
manifestRequests.push(req.url());
}
});

await app.goto("/", true);
expect(
await page.evaluate(() =>
Object.keys((window as any).__reactRouterManifest.routes)
)
).toEqual(["root", "routes/_index", "routes/a"]);
expect(manifestRequests).toEqual([
expect.stringMatching(/\/custom-manifest\?p=%2F&p=%2Fa&version=/),
]);
manifestRequests = [];

await app.clickLink("/a");
await page.waitForSelector("#a");
expect(await app.getHtml("#a")).toBe(`<h1 id="a">A: A LOADER</h1>`);
// Wait for eager discovery to kick off
await new Promise((r) => setTimeout(r, 500));
expect(manifestRequests).toEqual([
expect.stringMatching(/\/custom-manifest\?p=%2Fa%2Fb&version=/),
]);

expect(wrongManifestRequests).toEqual([]);
});

test.describe("routeDiscovery=initial", () => {
test("loads full manifest on initial load", async ({ page }) => {
let fixture = await createFixture({
files: {
...getFiles(),
"react-router.config.ts": reactRouterConfig({
routeDiscovery: { mode: "initial" },
}),
"app/entry.client.tsx": js`
import { HydratedRouter } from "react-router/dom";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<HydratedRouter discover={"none"} />
</StrictMode>
);
});
`,
},
});
let appFixture = await createAppFixture(fixture);

let manifestRequests: string[] = [];
page.on("request", (req) => {
if (req.url().includes("/__manifest")) {
manifestRequests.push(req.url());
}
});

let app = new PlaywrightFixture(appFixture, page);
let res = await fixture.requestDocument("/");
let html = await res.text();

expect(html).not.toContain("window.__reactRouterManifest = {");
expect(html).toContain(
'<link rel="modulepreload" href="/assets/manifest-'
);

// Linking to A succeeds
await app.goto("/", true);
expect(
await page.evaluate(() =>
Object.keys((window as any).__reactRouterManifest.routes)
)
).toEqual([
"root",
"routes/_index",
"routes/a",
"routes/a.b",
"routes/a.b.c",
]);

await app.clickLink("/a");
await page.waitForSelector("#a");
expect(await app.getHtml("#a")).toBe(`<h1 id="a">A: A LOADER</h1>`);
expect(manifestRequests).toEqual([]);
});

test("defaults to `routeDiscovery=initial` when `ssr:false` is set", async ({
page,
}) => {
let fixture = await createFixture({
spaMode: true,
files: {
"react-router.config.ts": reactRouterConfig({
ssr: false,
}),
"app/root.tsx": js`
import * as React from "react";
import { Link, Links, Meta, Outlet, Scripts } from "react-router";
export default function Root() {
let [showLink, setShowLink] = React.useState(false);
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body>
<Link to="/">Home</Link><br/>
<Link to="/a">/a</Link><br/>
<Outlet />
<Scripts />
</body>
</html>
);
}
`,
"app/routes/_index.tsx": js`
export default function Index() {
return <h1 id="index">Index</h1>
}
`,

"app/routes/a.tsx": js`
export function clientLoader({ request }) {
return { message: "A LOADER" };
}
export default function Index({ loaderData }) {
return <h1 id="a">A: {loaderData.message}</h1>
}
`,
},
});
let appFixture = await createAppFixture(fixture);

let manifestRequests: string[] = [];
page.on("request", (req) => {
if (req.url().includes("/__manifest")) {
manifestRequests.push(req.url());
}
});

let app = new PlaywrightFixture(appFixture, page);
let res = await fixture.requestDocument("/");
let html = await res.text();

expect(html).toContain('"routeDiscovery":{"mode":"initial"}');

await app.goto("/", true);
await page.waitForSelector("#index");
await app.clickLink("/a");
await page.waitForSelector("#a");
expect(await app.getHtml("#a")).toBe(`<h1 id="a">A: A LOADER</h1>`);
expect(manifestRequests).toEqual([]);
});

test("Errors if you try to set routeDiscovery=lazy and ssr:false", async () => {
let ogConsole = console.error;
console.error = () => {};
let buildStdio = new PassThrough();
let err;
try {
await createFixture({
buildStdio,
spaMode: true,
files: {
...getFiles(),
"react-router.config.ts": reactRouterConfig({
ssr: false,
routeDiscovery: { mode: "lazy" },
}),
},
});
} catch (e) {
err = e;
}

let chunks: Buffer[] = [];
let buildOutput = await new Promise<string>((resolve, reject) => {
buildStdio.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
buildStdio.on("error", (err) => reject(err));
buildStdio.on("end", () =>
resolve(Buffer.concat(chunks).toString("utf8"))
);
});

expect(err).toEqual(new Error("Build failed, check the output above"));
expect(buildOutput).toContain(
'Error: The `routeDiscovery.mode` config cannot be set to "lazy" when setting `ssr:false`'
);
console.error = ogConsole;
});
});
});
3 changes: 3 additions & 0 deletions integration/helpers/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export const reactRouterConfig = ({
splitRouteModules,
viteEnvironmentApi,
middleware,
routeDiscovery,
}: {
ssr?: boolean;
basename?: string;
Expand All @@ -41,12 +42,14 @@ export const reactRouterConfig = ({
>["unstable_splitRouteModules"];
viteEnvironmentApi?: boolean;
middleware?: boolean;
routeDiscovery?: Config["routeDiscovery"];
}) => {
let config: Config = {
ssr,
basename,
prerender,
appDirectory,
routeDiscovery,
future: {
unstable_splitRouteModules: splitRouteModules,
unstable_viteEnvironmentApi: viteEnvironmentApi,
Expand Down
3 changes: 2 additions & 1 deletion integration/vite-presets-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const files = {
export default {
// Ensure user config takes precedence over preset config
appDirectory: "app",

presets: [
// Ensure user config is passed to reactRouterConfig hook
{
Expand Down Expand Up @@ -221,6 +221,7 @@ test.describe("Vite / presets", async () => {
"future",
"prerender",
"routes",
"routeDiscovery",
"serverBuildFile",
"serverBundles",
"serverModuleFormat",
Expand Down
Loading